<?php

namespace AppBundle\Twig;

use AppBundle\Entity\User;
use AppBundle\Enum\UserType;
use AppBundle\Translation\ConstTranslator;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;

class ReplaceCustomKeywordExtension extends \Twig_Extension
{
    private $constTranslator;
    private $session;
    private $container;
    private $security;
    private $router;
    
    /**
     * Constructor
     * @param ConstTranslator $constTranslator
     * @param SessionInterface $session
     * @param ContainerInterface $container
     * @param Security $security
     */
    public function __construct(
        ConstTranslator $constTranslator,
        SessionInterface $session,
        ContainerInterface $container,
        Security $security,
        RouterInterface $router
    )
    {
        $this->constTranslator = $constTranslator;
        $this->session = $session;
        $this->container = $container;
        $this->security = $security;
        $this->router = $router;

        //$this->user = $this->security->getUser();
    }
    
    /**
     * Returns a list of filters.
     *
     * @return array
     */
    public function getFilters(): array
    {
        return [
            new \Twig_SimpleFilter('replace_custom_keys',  [$this, 'replace']),
        ];
    }

    public function replace($subject): string
    {
        $user = $this->security->getUser();
        $is_authenticated = (is_object($user) && $user instanceof User); 

        $dynamic_values = array(
            '/__LINK_ADD_OPE_ITDLC_DEPENDS_USER_TYPE__/' => $is_authenticated && $user->getType() == UserType::ENGINEER ? $this->router->generate('espace_perso_inge_itdlc') : $this->router->generate('espace_perso_prof_itdlc_add'),
            '/\[\s*IF TEACHER\s*\]\s*(.*)\s*\[\s*ENDIF\s*\]/' => $is_authenticated && $user->getType() == UserType::TEACHER ? '$1' : '',
            '/\[\s*IF ENGINEER\s*\]\s*(.*)\s*\[\s*ENDIF\s*\]/' => $is_authenticated && $user->getType() == UserType::ENGINEER ? '$1' : '',
            '/\[\s*IF USER CONNECTED\s*\]\s*(.*)\s*\[\s*ENDIF\s*\]/' => $is_authenticated ? '$1' : '',
            '/\[\s*IF USER NOT CONNECTED\s*\]\s*(.*)\s*\[\s*ENDIF\s*\]/' => !$is_authenticated ? '$1' : '',
        );
        
        return preg_replace(array_keys($dynamic_values), $dynamic_values, $subject);
    }
}
