<?php

namespace App\Controller;

use App\Entity\Adherent;
use App\Entity\Cotisation;
use App\Entity\Faq;
use App\Entity\Geoloc;
use App\Entity\Page;
use App\Entity\Siege;
use App\Entity\User;
use App\Entity\Usergroup;
use App\Enum\MoyenEnum;
use App\Form\Type\AdhererFormType;
use App\Form\Type\ContactFormType;
use App\Form\Type\InstallFormType;
use App\Form\Type\TransactionAdherentPrestataireFormType;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Geocoder\Provider\Nominatim\Nominatim;
use Geocoder\Query\GeocodeQuery;
use Nelmio\ApiDocBundle\Annotation\Model;
use Nelmio\ApiDocBundle\Annotation\Security;
use Swagger\Annotations as SWG;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security as Secur;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;

class IndexController extends AbstractController
{
    private $eventDispatcher;
    private $em;
    private $userManager;
    private $tokenManager;
    private $guard;

    public function __construct(EventDispatcherInterface $eventDispatcher, EntityManagerInterface $em, UserManagerInterface $userManager, CsrfTokenManagerInterface $tokenManager = null, GuardAuthenticatorHandler $guard)
    {
        $this->eventDispatcher = $eventDispatcher;
        $this->em = $em;
        $this->userManager = $userManager;
        $this->tokenManager = $tokenManager;
        $this->guard = $guard;
    }

    /**
     * @Route("/", name="index")
     */
    // public function index(TranslatorInterface $translator)
    public function index(Request $request)
    {
        // Exemple pour la traduction :
        // $translated = $translator->trans('Symfony is great');
        // $translator->transChoice(
        //     'Hurry up %name%! There is one apple left.|There are %count% apples left.',
        //     10,
        //     // no need to include %count% here; Symfony does that for you
        //     array('%name%' => $user->getName())
        // );

        /* Pour la première installation */
        $siege = $this->em->getRepository(Siege::class)->findAll();
        if ($siege == null || empty($siege)) {
            return $this->redirectToRoute('installation');
        }
        /* Pour la modale de login => SecurityController loginAction */
         /** @var $session Session */
        $session = $request->getSession();
        $lastUsernameKey = Secur::LAST_USERNAME;
        // last username entered by the user
        $lastUsername = (null === $session) ? '' : $session->get($lastUsernameKey);
        $csrfToken = $this->tokenManager
            ? $this->tokenManager->getToken('authenticate')->getValue()
            : null;

        return $this->render('index.html.twig', [
            'news' => array(),
            'last_username' => $lastUsername,
            'csrf_token' => $csrfToken
        ]);
    }

    /**
     * @Route("/installation", name="installation")
     */
    public function installationAction(Request $request)
    {
        $siege = $this->em->getRepository(Siege::class)->findOneById(1);
        if (!empty($siege)) {
            return $this->redirectToRoute('index');
        }
        $user = $this->userManager->createUser();
        $repogroup = $this->em->getRepository(Usergroup::class);
        $group = $repogroup->findOneBy(array('name' => 'Super Admin'));
        $user->setEnabled(true);
        $user->addGroup($group);
        $user->addRole('ROLE_SUPER_ADMIN');
        $form = $this->createForm(InstallFormType::class, ['user' => $user]);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $siege = $form['siege']->getData();
            $user = $form['user']->getData();
            $this->userManager->updateUser($user);
            $this->em->persist($siege);
            $this->em->persist($user);
            // TODO : send mail
            $this->addFlash(
                'success',
                'BRAVO ! Vous avez créer le siège et le premier utilisateur'
            );
            // if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('fos_user_registration_confirmed');
                $response = new RedirectResponse($url);
            // }

            $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
            $referer = $request->headers->get('referer');
            if ($referer && !$request->isXmlHttpRequest()) {
                return $this->redirect($referer);
            } elseif (!$request->isXmlHttpRequest()) {
                return new Response('', Response::HTTP_BAD_REQUEST);
            }
        }
        return $this->render('installation.html.twig', array(
            'form' => $form->createView()
        ));
    }

    /**
     * @Route("/adherer", name="adherer")
     */
    public function adhererAction(Request $request)
    {
        // @TODO : formulaire d'adhésion sans cotisation ? à valider après ?

        $adherent = new Adherent();
        $user = $this->userManager->createUser();
        $groupe = $this->em->getRepository(Usergroup::class)->findOneByName('Adherent');
        $user->setEnabled(false);
        $user->addGroup($groupe);
        $user->addRole('ROLE_ADHERENT');
        $adherent->setEcompte('0');
        $user->setAdherent($adherent);
        $adherent->setUser($user);
        if (count($adherent->getUser()->getCotisations()) <= 0) {
            $cotisation = new Cotisation();
            $cotisation->setMontant(floatval($this->getParameter('app.cotisation_montant')));
            $cotisation->setOperateur($adherent->getUser());
            $cotisation->setExpediteur($adherent);
            $cotisation->setMoyen(MoyenEnum::MOYEN_AUTRE);
            $cotisation->setDebut(new \DateTime());
            $cotisation->setFin(new \DateTime('+ 1 year'));
            $adherent->getUser()->addCotisation($cotisation);
        }
        if ($adherent->getGeoloc() == null) {
            $adherent->setGeoloc(new Geoloc());
        }
        $form = $this->createForm(AdhererFormType::class, $adherent);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $adherentNew = $form->getData();
                $cotisationNew = $form['cotisation']->getData();
                // dump($adherentNew);
                // dump($cotisationNew);
                // exit();
                // $adherentNew->getUser()->removeCotisation($cotisation);
                $this->em->persist($cotisationNew);
                $adherentNew->getUser()->addCotisation($cotisationNew);
                $this->em->persist($adherentNew);
                $this->em->persist($adherentNew->getUser());
                $this->em->flush();
                $this->addFlash(
                    'success',
                    'Adhésion bien pris en compte, vous recevrez un email très bientôt !'
                );
                return $this->redirectToRoute('index');
            } else {
                $this->addFlash(
                    'error',
                    'Problème avec l\'adhésion !'
                );
            }
        }

        return $this->render('adherent/adherer.html.twig', array(
            'form' => $form->createView()
        ));
    }

    /**
     * @Route("/group/choice/{id}", name="group_choice")
     */
    public function groupChoiceAction(Usergroup $group, Request $request)
    {
        $request->getSession()->remove('_choixGroup');
        // On enregistre le rôle choisit en session
        $request->getSession()->set('_groupId', $group);

        // @TODO : On redirige sur l'index (ou en fonction du rôle?)
        return $this->redirectToRoute('index');
    }

    /**
     * @Route("/page/{slug}", name="show_page")
     */
    public function pageAction(Page $page)
    {
        $template = 'page.html.twig';
        if (!empty($page->getTemplate()) && $this->get('templating')->exists($page->getTemplate())) {
            $template = $page->getTemplate();
        }
        return $this->render($template, array(
            'page' => $page
        ));
    }

    /**
     * @Route("/faq", name="faq")
     */
    public function faqAction()
    {
        return $this->render('faq/liste.html.twig', array(
            'faqs' => $this->em->getRepository(Faq::class)->findBy(array('enabled' => true), array('createdAt' => 'DESC'))
        ));
    }


    /**
     * @Route("/faq/{slug}", name="show_faq")
     */
    public function showFaqAction(Faq $faq)
    {
        return $this->render('faq/show.html.twig', array(
            'faq' => $faq
        ));
    }

    /**
     * @Route("/contact", name="contact")
     */
    public function contactAction(Request $request)
    {
        $form = $this->createForm(ContactFormType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $nom = $form['nom']->getData();
            $emailFrom = $form['email']->getData();
            $message = $form['message']->getData();
            // TODO : send mail
            $this->addFlash(
                'success',
                'Merci ! Le message a bien été envoyé !'
            );
            $referer = $request->headers->get('referer');
            if ($referer && !$request->isXmlHttpRequest()) {
                return $this->redirect($referer);
            } elseif (!$request->isXmlHttpRequest()) {
                return new Response('', Response::HTTP_BAD_REQUEST);
            }
        }
        return $this->render('contact.html.twig', array(
            'form' => $form->createView()
        ));
    }
}