<?php

namespace App\Twig;

use App\Entity\Comptoir;
use App\Entity\Flux;
use App\Entity\Groupe;
use App\Entity\Groupeprestataire;
use App\Entity\News;
use App\Entity\Prestataire;
use App\Entity\Rubrique;
use App\Entity\Siege;
use App\Entity\User;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;

class AppExtension extends AbstractExtension
{
    public $container;
    public $paginator;

    public function __construct($container, $paginator)
    {
        $this->container = $container;
        $this->paginator = $paginator;
    }

    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('getSiege', array($this, 'getSiege')),
            new \Twig_SimpleFunction('getLastNews', array($this, 'getLastNews')),
            new \Twig_SimpleFunction('getAllPrestataires', array($this, 'getAllPrestataires')),
            new \Twig_SimpleFunction('getAllGroupePrestataires', array($this, 'getAllGroupePrestataires')),
            new \Twig_SimpleFunction('getAllComptoirs', array($this, 'getAllComptoirs')),
            new \Twig_SimpleFunction('getAllRubriques', array($this, 'getAllRubriques')),
            new \Twig_SimpleFunction('getAllGroupes', array($this, 'getAllGroupes')),
            new \Twig_SimpleFunction('getAllFlux', array($this, 'getAllFlux')),
            new \Twig_SimpleFunction('mediaurl', array($this, 'mediaurl')),
            new \Twig_SimpleFunction('parameter', function ($name) {
                return $this->container->getParameter($name);
            })
        ];
    }

    public function getSiege()
    {
        return $this->container->get('doctrine')->getRepository(Siege::class)->findOneById(1);
    }

    public function getLastNews($limit = 5)
    {
        return $this->container->get('doctrine')->getRepository(News::class)->findBy(array('enabled' => true), array('createdAt' => 'DESC'), $limit);
    }

    public function getAllPrestataires()
    {
        return $this->container->get('doctrine')->getRepository(Prestataire::class)->findBy(array('enabled' => true), array('raison'=> 'ASC'));
    }

    public function getAllGroupePrestataires($type = '')
    {
        return $this->container->get('doctrine')->getRepository(Groupeprestataire::class)->findBy(array('type' => $type, 'enabled' => true));
    }

    public function getAllComptoirs()
    {
        return $this->container->get('doctrine')->getRepository(Comptoir::class)->findBy(array('enabled' => true), array('name'=> 'ASC'));
    }

    public function getAllRubriques()
    {
        return $this->container->get('doctrine')->getRepository(Rubrique::class)->findBy(array('enabled' => true), array('name'=> 'ASC'));
    }

    /**
     * Return a list of all filters.
     *
     * @return array
     */
    public function getFilters()
    {
        return [
            new \Twig_SimpleFilter('safe_email', [$this, 'safeEmailFilter']),
        ];
    }

    public function getAllFlux(User $user, Request $request)
    {
        $query = null;
        if ($user->getPrestataire() != null) {
            $query = $this->container->get('doctrine')->getRepository(Flux::class)->getQueryByPrestataire($user->getPrestataire());
        } else if ($user->getAdherent() != null) {
            $query = $this->container->get('doctrine')->getRepository(Flux::class)->getQueryByAdherent($user->getAdherent());
        } else if ($user->getComptoirsgere() != null) {
            $query = $this->container->get('doctrine')->getRepository(Flux::class)->getQueryByComptoir($user->getComptoirsgere());
        } else if ($user->getGroupesgere() != null) {
            $query = $this->container->get('doctrine')->getRepository(Flux::class)->getQueryByGroupe($user->getGroupesgere());
        }
        if ($query != null) {
            $pagination = $this->paginator->paginate(
                $query, /* query NOT result */
                $request->query->getInt('page', 1)/*page number*/,
                10/*limit per page*/
            );

            return $pagination;
        }
        return null;
    }

    public function getAllGroupes()
    {
        return $this->container->get('doctrine')->getRepository(Groupe::class)->findBy(array('enabled' => true), array('name'=> 'ASC'));
    }

    public function mediaurl($media, $format)
    {
        $provider = $this->container->get($media->getProviderName());
        return $provider->generatePublicUrl($media, $format);
    }

    public function getTests(): array
    {
        return [
            new TwigTest('instanceof', [$this, 'instanceof']),
        ];
    }

    public function instanceof($var, $instance)
    {
        $reflexionClass = new \ReflectionClass($instance);
        return $reflexionClass->isInstance($var);
    }

    /**
     * Protects email address.
     * (inspired by : https://github.com/getgrav/grav/blob/develop/system/src/Grav/Common/Twig/TwigExtension.php )
     *
     * @param  string $str
     *
     * @return string
     */
    public function safeEmailFilter($str)
    {
        $email   = '';
        for ($i=0, $len = strlen($str); $i < $len; $i++) {
            $j = mt_rand(0, 1);
            if ($j === 0) {
                $email .= '&#'.ord($str[$i]).';';
            } else if ($j === 1) {
                $email .= $str[$i];
            }
        }
        return str_replace('@', '&#64;', $email);
    }
}
