<?php

namespace App\Twig;

use App\Entity\Comptoir;
use App\Entity\Flux;
use App\Entity\Groupe;
use App\Entity\News;
use App\Entity\Prestataire;
use App\Entity\Rubrique;
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('getLastNews', array($this, 'getLastNews')),
            new \Twig_SimpleFunction('getAllPrestataires', array($this, 'getAllPrestataires')),
            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 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));
    }

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

    public function getAllRubriques()
    {
        return $this->container->get('doctrine')->getRepository(Rubrique::class)->findBy(array('enabled' => true));
    }
    /**
     * 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());
        }
        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));
    }

    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);
    }
}
