<?php

namespace App\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class BlogExtension extends AbstractExtension
{
    public function getName()
    {
        return 'blog_extension';
    }

    public function getFilters()
    {
        return [
            new TwigFilter('comment', [$this, 'comment'], ['is_safe' => ['html']]),
            new TwigFilter('post', [$this, 'post'], ['is_safe' => ['html']]),
        ];
    }

    public function comment($text)
    {
        $text = htmlspecialchars(trim($text)).' ';

        $text = preg_replace_callback(
            '`(s?(http|ftp|irc)+s?://[^\s\)]+)(\s|\))+`iU',
            function ($data) {
                return sprintf('<a target="_blank" href="%s">%s</a>%s', htmlspecialchars($data[1]), htmlspecialchars($data[1]), $data[3]);
            },
            $text
        );

        return nl2br($text);
    }

    public function post($text)
    {
        $text = str_replace('http://upload.deblan.fr', 'https://upload.deblan.org', $text);
        $text = str_replace('http://dedi.geneweb.fr', 'http://kim.deblan.fr', $text);
        $text = str_replace('http://mediaplayer.deblan.fr', 'https://mediaplayer.deblan.org', $text);
        $text = str_replace('http://blog.deblan.fr', 'https://www.deblan.io', $text);
        $text = str_replace('http://www.deblan.tv', 'https://www.deblan.io', $text);

        $text = preg_replace_callback(
            '`<p([^>]*)>(.*)</p([^>]*)>`isU',
            function ($data) {
                if (preg_match('`^[ ]+`', $data[1])) {
                    return '<p'.$data[1].'>'.nl2br(trim($data[2])).'</p>';
                }
                if (isset($data[1]) && '' === $data[1]) {
                    return '<p>'.nl2br(trim($data[2])).'</p>';
                }

                return $data[0];
            },
            $text
        );

        foreach (['centre', 'droite', 'flgauche', 'fldroite', 'clear'] as $tag) {
            $regex = sprintf('`<%1$s>(.*)</%1$s>`', $tag);

            $text = preg_replace_callback(
                $regex,
                function ($data) {
                    return '<div>'.$data[1].'</div>';
                },
                $text
            );
        }

        foreach (['titre', 'titre'] as $k => $tag) {
            $regex = sprintf('`<%1$s>(.*)</%1$s>`', $tag);

            $text = preg_replace_callback(
                $regex,
                function ($data) use ($k) {
                    return '<div class="h'.($k + 3).'">'.$data[1].'</div>';
                },
                $text
            );
        }

        foreach ([
            '`<sondage>([0-9]+)</sondage>`isU',
            '`<object(.*)/object>`isU',
            '`smiley:([a-zA-Z]*)`is',
            '#<couper>#isU',
            "#onclick='window\\.open\\(this\\.href\\); return false'#",
            '#<timestamp>#isU',
            '#&lt;timestamp&gt;#isU',
        ] as $regex) {
            $text = preg_replace($regex, '', $text);
        }

        $text = preg_replace_callback('`<li>(.*)</li>`isU', function ($data) {
            return '<li>'.trim($data[1]).'</li>';
        }, $text);

        $text = preg_replace_callback(
            '`<quote auteur=["\']{1}([^\']+)["\']{1}>(.*)</quote>`isU',
            function ($data) {
                return sprintf('<blockquote><p>%s</p><p><em>%s</em></p></blockquote>', nl2br(trim($data[2])), $data[1]);
            },
            $text
        );

        $text = preg_replace_callback(
            '`<quote>(.*)</quote>`isU',
            function ($data) {
                return sprintf('<blockquote><p>%s</p></blockquote>', nl2br(trim($data[1])));
            },
            $text
        );

        $text = preg_replace_callback('`<html>(.*)</html>`isU', function ($data) {
            return html_entity_decode($data[1]);
        }, $text);

        $text = preg_replace_callback('`<encode>(.*)</encode>`isU', function ($data) {
            return htmlspecialchars($data[1]);
        }, $text);

        $text = preg_replace('`<sondage>([0-9]+)</sondage>`isU', '', $text);

        $text = preg_replace_callback('`<nonl2br>(.*)</nonl2br>`isU', function () {
            return str_replace('<br />', '', $data[1]);
        }, $text);

        $text = preg_replace_callback(
            [
                '#<code langage="([^"]*)">(.*)</code>#isU',
                '#<code langage=\'([^\']*)\'>(.*)</code>#isU',
            ],
            function ($data) {
                $lang = strtolower(str_replace(
                    ['console', 'texte', 'apache'],
                    ['bash', 'text', 'html'],
                    $data[1])
                );
                $class = 'language-'.$lang;

                return sprintf('<pre><code class="%s">%s</code></pre>', $class, trim(htmlentities($data[2])));
            },
            $text
        );

        $text = preg_replace_callback('`<url>([^<]+)</url>`isU', function ($data) {
            return '<a href="'.$data[1].'">'.$data[1].'</a>';
        }, $text);

        $text = preg_replace_callback('`<galerie>(.*)</galerie>`isU', function ($data) {
            $lines = explode("\n", $data[1]);
            $pictures = [];

            foreach ($lines as $line) {
                $line = trim($line);

                if (empty($line)) {
                    continue;
                }

                $elements = explode('|', $line);

                if (2 === count($elements) || 3 === count($elements)) {
                    $pictures[] = sprintf(
                        '<li><a href="%1$s" target="_blank"><img class="border" src="%2$s" alt="%3$s" title="%3$s"></a></li>',
                        $elements[0],
                        $elements[1],
                        isset($elements[2]) ? $elements[2] : ''
                    );
                }
            }

            if (empty($pictures)) {
                return '';
            }

            return '<ul class="list--inline">'.implode('', $pictures).'</ul>';
        }, $text);

        foreach (['`"http://www.youtube.com/[^"]+"`i', '`"http://www.dailymotion.com/[^"]+"`i'] as $regex) {
            $text = preg_replace_callback($regex, function ($data) {
                return str_replace('&', '&amp;', $data[0]);
            }, $text);
        }

        return $text;
    }
}
