<?php
namespace Skeleton\Renderer;

use Psr\Container\ContainerInterface;
use Helpers\Session\ParseBase1;

class TwigRendererFactory
{
    
    public function __invoke(ContainerInterface $container)
    {
        $viewPath = $container->get('views.path');
        $loader = new \Twig\Loader\FilesystemLoader($viewPath);
        if (isset($_SESSION['environnement']) && $_SESSION['environnement'] =='production') {
            $twig = new \Twig\Environment($loader, array(
                'cache' =>  (new ParseBase1())->getRep()->tmp.'cache-framework/'.$_SESSION['cache'],
                'debug' => false,
                'auto_reload' => true
            ));
        } else {
            $twig = new \Twig\Environment($loader);
        }
        if ($container->has('twig.extensions')) {
            foreach ($container->get('twig.extensions') as $extension) {
                $twig->addExtension($extension);
            }
        }
        
        
        if (isset($_SESSION['Session_NumClient']) && $_SESSION['Session_NumClient'] != '') {
            if ($container->has('twig.extensions'.$_SESSION['Session_NumClient'])) {
                foreach ($container->get('twig.extensions'.$_SESSION['Session_NumClient']) as $extension) {
                    $twig->addExtension($extension);
                }
            }
        }

        $urls = explode('/', $_SERVER['REQUEST_URI']);
        if ($urls[2] == 'V2') {
            $module = $urls[3];
        } else {
            $module = $urls[2];
        }
        if ($container->has('twig.extensions.'.$module)) {
            foreach ($container->get('twig.extensions.'.$module) as $extension) {
                $twig->addExtension($extension);
            }
        }
        return new TwigRenderer($loader, $twig);
    }

    /**
     * getModules
     *
     * @return array<mixed>
     */
    public static function getAllTwigExtensions() :array
    {
        $listTwigExt = require_once __DIR__.'/../../../config/TwigExtention/configTwigExtention.php';
        return array_map(function ($twigExt) {
            return \DI\get($twigExt);
        }, $listTwigExt);
    }
}
