<?php

namespace Diamond;

use Core\Exceptions\NoAccess;
use Core\Exceptions\PageNotFound;
use Diamond\Application\System\SystemService;
use Diamond\Config\Counters;
use Diamond\Config\Main;
use Diamond\Helpers\Date;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Request;
use Twig\TwigFunction;
use function dump;
use Core\Application\Loader as App;
use Core\Template\Template;

/**
 * Расширение функций для твига
 *
 * @author Admin
 */
class TwigExtensions extends \Twig\Extension\AbstractExtension
{

    private static function getCompanyLogoImg(): string
    {
        return !defined('ADMIN_COMPANY_LOGO') ? '/_diamond/diamond-cms/assets/images/company-logo.png' : ADMIN_COMPANY_LOGO;
    }

    /**
     * @return array|\Twig\TwigFunction[]
     */
    public function getFunctions()
    {
        return array(

            new TwigFunction('admin_company_logo',
                function () {
                    return self::getCompanyLogoImg();
                }, ['is_safe' => ['html']]),

            new TwigFunction('admin_company_title',
                function () {
                    /** @var Main $conf */
                    $conf = App::getInstance()->load('DI')->get(Main::class);
                    $siteName = $conf->getSite_name();
                    return !defined('ADMIN_COMPANY_TITLE') ? ' <img class="brand-icon" src="' . self::getCompanyLogoImg() . '">' .
                        '<div class="brand-title"><span class="brand-text">' . $siteName .
                        '</span></div>' : ADMIN_COMPANY_TITLE;
                }, ['is_safe' => ['html']]),
            //module render
            new TwigFunction('admin_path',
                function (?string $path = null) {
                    return admin_path($path);
                }),
            //module render
            new TwigFunction('module',
                function ($name, array $params = []) {
                    if (preg_match('|^(.*?)\.(.*?)$|is', $name, $m)) {
                        $name = sprintf("%s\\Modules\\%s\\%s", $m[1], $m[2], $m[2]);
                    }

                    return App::getModule($name, $params);

                }, ['is_safe' => ['html']]),
            //test_modules
            new TwigFunction('test_modules',
                function ($name) {

                    $autoload = include BASEPATH . '/vendor/autoload.php';

                    foreach ($autoload->getClassMap() as $class => $path) {
                        if (stripos($class, $name . '\\Modules') !== false) {
                            $dir = dirname($path, 2);
                            break;
                        }
                    }
                    $finder = new Finder();

                    $iterator = $finder->directories()->depth(0)->in($dir);

                    foreach ($iterator as $file) {
                        try {
                            dump(App::getModule($name . '.' . $file->getrelativePathname()));
                        } catch (NoAccess|PageNotFound $ex) {

                        }
                    }

                    return '';

                }, ['is_safe' => ['html']]),
            //dump
            new TwigFunction('dump',
                function ($data) {
                    dump($data);
                }, ['is_safe' => ['html']]),
            //anchor
            new TwigFunction('anchor',
                function ($_url, $_title, $params = [], $url_params = []) {
                    return Helpers\Url::anchor($_url, $_title, $params, $url_params);
                }, ['is_safe' => ['html']]),
            //template styles
            new TwigFunction('template_styles', function (array $css, $cssPath = null, $cssTemplatePath = null, $js_path = null) {
                return App::getInstance()
                    ->load('DI')
                    ->get(SystemService::class)
                    ->getTemplateStyles($css, $cssPath, $cssTemplatePath, $js_path);
            }, ['is_safe' => ['html']]),

            new TwigFunction('template_header_styles_render', function (array $css = []) {

                $templater = App::getInstance()
                    ->load('DI')
                    ->get(Template::class);

                $styles = App::getInstance()
                    ->load('DI')
                    ->get(SystemService::class)
                    ->getTemplateStyles($templater->getHeaderStyles());

                $html = '';

                foreach ($styles as $link) {
                    $html .= '<link href="' . $link . '" rel="stylesheet">' . PHP_EOL;
                }

                return $html;
            }, ['is_safe' => ['html']]),

            new TwigFunction('template_styles_render', function (array $css = []) {
                $templater = App::getInstance()
                    ->load('DI')
                    ->get(SystemService::class);

                $scripts = $templater
                    ->getTemplateStyles($css, '', '', '');
                $html = '';
                foreach ($scripts as $link) {
                    $html .= '<link href="' . $link . '" rel="stylesheet">' . PHP_EOL;
                }

                return $html;
            }, ['is_safe' => ['html']]),
            //template style
            new TwigFunction('template_style', function () {
                return App::getInstance()->load('DI')->get(Template::class)->getStyle();
            }, ['is_safe' => ['html']]),
            //template script
            new TwigFunction('template_script', function () {
                return App::getInstance()->load('DI')->get(Template::class)->getScript();
            }, ['is_safe' => ['html']]),

            new TwigFunction('template_script_style', function () {
                $template = App::getInstance()->load('DI')->get(Template::class);
                return $template->getScript() . $template->getStyle();
            }, ['is_safe' => ['html']]),

            //template scripts
            new TwigFunction('template_scripts', function (array $js, $jsPath = null, $jsTemplatePath = null) {
                return App::getInstance()
                    ->load('DI')
                    ->get(SystemService::class)
                    ->prepareTemplateScripts($js, $jsPath, $jsTemplatePath);
            }, ['is_safe' => ['html']]),

            new TwigFunction('template_scripts_render', function (array $js = []) {
                $scripts = App::getInstance()
                    ->load('DI')
                    ->get(SystemService::class)
                    ->prepareTemplateScripts($js, '', '');

                $html = '';
                foreach ($scripts as $link) {
                    $html .= '<script src="' . $link . '"></script>' . PHP_EOL;
                }
                return $html;
            }, ['is_safe' => ['html']]),

            //template dubug
            new TwigFunction('template_debug', function () {

                /**
                 * @var Request $request
                 */
                $request = App::getInstance()->load('DI')->get(Request::class);

                $ip = $request->getClientIp();


                if (getenv('DEBUG_IP')) {
                    $access = getenv('DEBUG_IP');
                }
                else{
                    $access = $ip;
                }

                /**
                 * @var \DebugBar\StandardDebugBar $debugbar
                 */
                $debugbar = App::getInstance()->load('DI')->get(\DebugBar\StandardDebugBar::class);
                $debugbarRenderer = $debugbar->getJavascriptRenderer('/_diamond/diamond-cms/assets/debug_bar');
                $debugHtml = $debugbarRenderer->render(true, false);

                if (getenv('MODE') === 'dev') {
            
                    $pattern = str_replace(
                        ['*', '.'],
                        ['\d+', '\.'],
                        $access
                    );
                    $pattern = '/^' . $pattern . '$/';

                    if(preg_match($pattern, $ip)){
                        return $debugbarRenderer->renderHead() . $debugHtml;
                    }

                    return '';
                }

                return '';

            }, ['is_safe' => ['html']]),
            //header
            //есть ли уже заголовок на странице
            new TwigFunction('page_header', function () {
                $request = App::getInstance()->load('DI')->get(Request::class);
                if (preg_match("~^\/.*\/.*\/\d+-.*~", $request->getPathInfo())) {
                    return true;
                }

                return false;
            }),
            //site name                
            new TwigFunction('format_site_name', function ($title) {
                if (preg_match('~(.*)\.(.*)~s', $title, $match)) {
                    $title = "<span>{$match[1]}.</span>{$match[2]}";
                }
                return strtoupper($title);
            }, ['is_safe' => ['html']]),


            //site name
            new TwigFunction('bg_image_style', function () {


                if (!defined('ADMIN_IMAGE')) {
                    return '';
                }

                return 'style="background-image: url(' . ADMIN_IMAGE . ')"';
            }, ['is_safe' => ['html']]),


            //current url
            new TwigFunction('isHome', function () {

                $cur = Request::createFromGlobals()->getPathInfo();

                return $cur === '/';
            }),

            //current url
            new TwigFunction('current_url', function () {
                return current_url();
            }, ['is_safe' => ['html']]),
            //adaptive url
            new TwigFunction('adaptive_url', function ($params = [], $ignore = []) {
                return adaptive_url($params, $ignore);
            }, ['is_safe' => ['html']]),


            new TwigFunction('last_time', function ($time) {
                return Date::lastTime($time);
            }, ['is_safe' => ['html']]),

            new TwigFunction('left_menu_toogle', function () {
                $request = App::getInstance()->load('DI')->get(Request::class);
                if ($request->cookies->get('leftmenu') === 'collapsed') {
                    return 'mainnav-sm';
                }
                return 'mainnav-lg';
            }),

            new TwigFunction('top_counters', function () {
                return App::getInstance()->load('DI')->get(Template::class)->getTop_counters();
            }, ['is_safe' => ['html']]),

            new TwigFunction('bottom_counters', function () {
                return App::getInstance()->load('DI')->get(Template::class)->getBootom_counters();
            }, ['is_safe' => ['html']]),
        );
    }


}