<?php

namespace App\Controller\Admin;

use App\Entity\User\User;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\ArrayField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\EmailField;
use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
use Lc\SovBundle\Controller\User\UserAdminController as AbstractUserCrudController;
use Lc\SovBundle\Definition\RolesDefinitionInterface;
use Lc\SovBundle\Doctrine\EntityManager;
use Lc\SovBundle\Repository\RepositoryQueryInterface;
use Lc\SovBundle\Translation\TranslatorAdmin;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mime\Message;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Twig\Environment;

class UserCrudController extends AbstractUserCrudController
{
    protected $passwordEncoder;
    protected $entityManager;
    protected $mailerInterface;

    public function __construct(
        SessionInterface $session,
        RequestStack $request,
        EntityManager $em,
        TranslatorAdmin $translatorAdmin,
        RolesDefinitionInterface $rolesDefinition,
        UserPasswordEncoderInterface $passwordEncoder,
        EntityManager $entityManager,
        MailerInterface $mailerInterface
    )
    {

        $this->passwordEncoder = $passwordEncoder;
        $this->entityManager = $entityManager;
        $this->mailerInterface = $mailerInterface;

        parent::__construct($session, $request, $em, $translatorAdmin, $rolesDefinition);
    }

    public static function getEntityFqcn(): string
    {
        return User::class;
    }

    public function getRepositoryQuery(): RepositoryQueryInterface
    {
        return $this->getUserContainer()->getRepositoryQuery();
    }

    public function configureFields(string $pageName): iterable
    {
        return [
            TextField::new('firstname'),
            TextField::new('lastname'),
            EmailField::new('email'),
            ChoiceField::new('roles')
                ->allowMultipleChoices()
                ->autocomplete()
                ->setChoices(["Utilisateur" => "ROLE_USER", "Animateur" => "ROLE_ANIMATOR", "Admin" => "ROLE_ADMIN"]),

        ];
    }

    public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
    {

        // @TODO : gérer avec UserManager
        $plainPassword = $this->generatePassword(12, 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN123456789#!?+=-/%');
        $newPasswordEncoded = $this->passwordEncoder->encodePassword($entityInstance, $plainPassword);
        $entityInstance->setPassword($newPasswordEncoded);

        $this->entityManager->create($entityInstance);
        $this->entityManager->flush();

        $email = (new TemplatedEmail())
            ->from('contact@laclic.fr')
            ->to($entityInstance->getEmail())
            ->subject('Mot de passe Aux Actes Citoyens')
            ->htmlTemplate('emails/password.html.twig')
            ->context([
                'password' => $plainPassword,
                'firstname' => $entityInstance->getFirstname(),
                'lastname' => $entityInstance->getLastname(),
            ]);

        $this->mailerInterface->send($email);

        parent::persistEntity($entityManager, $entityInstance);
    }

    function generatePassword($caracteres = 12, $chaine = 'azertyuiopqsdfghjklmwxcvbnAZERTYUIOPQSDFGHJKLMWXCVBN123456789#!?+=-/%')
    {
        $nb_lettres = strlen($chaine) - 1;
        $generation = '';
        for ($i = 0; $i < $caracteres; $i++) {
            $pos = mt_rand(0, $nb_lettres);
            $car = $chaine[$pos];
            $generation .= $car;
        }
        return $generation;
    }

}
