<?php

namespace AppBundle\Controller\Legacy;

use AppBundle\Entity\Availability;
use AppBundle\Entity\OperationITDLC;
use AppBundle\Enum\OperationITDLCState;
use AppBundle\Enum\OperationITDLCType;
use AppBundle\Enum\UserType;
use AppBundle\Form\Type\AvailabilityHebdoType;
use AppBundle\Form\Type\AvailabilityPrecisType;
use AppBundle\Form\Type\Front\ITDLC\Legacy\IngeDemandeITDLCType;
use AppBundle\Form\Type\Front\ITDLC\Legacy\ProfDemandeITDLCType;
use AppBundle\Mail\ItdlcMailer;
use Doctrine\ORM\EntityManagerInterface;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Translation\TranslatorInterface;


class OperationItdlcController extends Controller
{
    /**
     * @var EventDispatcherInterface
     */
    private $dispatcher;
    
    /**
     * @var EntityManagerInterface
     */
    private $em;

    /**
     * @var ItdlcMailer
     */
    private $itdlcMailer;

    /**
     * @var TranslatorInterface
     */
    private $translator;

    /**
     * @var UserManagerInterface
     */
    private $userManager;

    /**
     * @var SessionInterface
     */
    private $session;

    
    public function __construct(
        EventDispatcherInterface $dispatcher, 
        EntityManagerInterface $em, 
        ItdlcMailer $itdlcMailer,
        TranslatorInterface $translator,
        UserManagerInterface $userManager,
        SessionInterface $session
    )
    {
        $this->dispatcher = $dispatcher;
        $this->em = $em;
        $this->itdlcMailer = $itdlcMailer;
        $this->translator = $translator;
        $this->userManager = $userManager;
        $this->session = $session;
    }

    /**
     * Ajout d'une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/legacy/espace-perso/demande-itdlc-p/add",
     *      name = "legacy_espace_perso_prof_itdlc_add"
     * )
     *
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     * @throws \Exception
     */
    public function addProfITDLCAction(Request $request)
    {
        $user = $this->getUser();
        
        // Stock return path in session and redirect to login if user is anonymous
        if (!is_object($user) || !$user instanceof UserInterface) {
            $this->session->set('_return', base64_encode($this->generateUrl($request->get('_route'), $request->get('_route_params'), UrlGeneratorInterface::ABSOLUTE_URL)));

            return $this->redirectToRoute('fos_user_security_login');
        }
        
        if (UserType::TEACHER !== $user->getType()) {
            //throw $this->createAccessDeniedException();

            $this->addFlash('error', $this->translator->trans(
                'notice.user.access_denied',
                [],
                'notice'
            ));
            return new RedirectResponse($this->generateUrl('espace_perso'));
        }

        // Formulaire page simple 
        $ope = new OperationITDLC;
        $form = $this->createForm(ProfDemandeITDLCType::class, $ope);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // On enregistre le contenu de la demande 
            $ope->setType(OperationITDLCType::DEMANDE);
            $ope->setState(OperationITDLCState::NEW);
            $ope->setProf($user);

            $this->em->persist($ope);
            $this->em->flush();

            $this->itdlcMailer->confirmDemande($user);

            $this->addFlash('success', 'Demande enregistrée');

            return $this->redirectToRoute('espace_perso_prof_itdlc_edit', array(
                'ope'=>$ope->getId(),
                'mode'=>'edit',
            ));
        }

        return $this->render('Front/Demande/ITDLC/form.html.twig', array(
            'form' => $form->createView(),
            'type'=>'Demande Ingénieurs et Techniciens dans les classes',
            'mode'=>'add',
        ));
    }

    /**
     * Modification d'une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/legacy/espace-perso/demande-itdlc-p/edit/{ope}",
     *      name = "legacy_espace_perso_prof_itdlc_edit"
     * )
     * @ParamConverter("ope", class = "AppBundle:OperationITDLC", options = {
     *      "repository_method" = "findAllWithAvailabilities",
     *      "mapping": {"ope": "operationId"},
     *      "map_method_signature" = true
     * })
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editProfITDLCAction(Request $request, OperationITDLC $ope)
    {
        $user = $this->getUser();

        if (UserType::TEACHER !== $user->getType() || $user->getId() !== $ope->getProf()->getId()) {
            //throw $this->createAccessDeniedException();
            $this->addFlash('error', $this->translator->trans(
                'notice.user.access_denied',
                [],
                'notice'
            ));
            return new RedirectResponse($this->generateUrl('espace_perso'));
        }

        if (OperationITDLCType::OPERATION === $ope->getType()) {
            //throw $this->createAccessDeniedException('Vous ne pouvez pas éditer une opération');
            $this->addFlash('error', $this->translator->trans(
                'notice.demandeITDLC.error.operation.cant_edit',
                [],
                'notice'
            ));
            return new RedirectResponse($this->generateUrl('espace_perso'));
        }

        $form = $this->createForm(ProfDemandeITDLCType::class, $ope);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->em->persist($ope);
            $this->em->flush();

            $subject = 'Venez visiter le site cgenial.org';
            $body = str_replace("\n", '%0D%0A', // Required for line break representation in the mailto: URL scheme
                $this->renderView('Front/Mail/invitation.html.twig', array(
                    'firstname' => $user->getFirstname(),
                    'lastname' => $user->getLastname(),
                ))
            );

            $flash = $this->renderView('Front/Flash/confirm-itdlc.html.twig', [
                'subject' => $subject,
                'body' => $body,
                'addPeeUrl' => $this->generateUrl('espace_perso_pee_add'),
                'addItdlcUrl' => $this->generateUrl('espace_perso_prof_itdlc_add'),
            ]);

            $this->addFlash('info', $flash);

            return $this->redirectToRoute('espace_perso');
        }

        return $this->render('Front/Demande/ITDLC/form.html.twig', array(
            'form' => $form->createView(),
            'type' => 'Demande Ingénieurs et Techniciens dans les classes',
            'mode' => 'edit',
            'ope' => $ope,
        ));
    }

    /**
     * Ajout / modification d'une demande ITDLC ingénieur
     *
     * @Route(
     *      "/legacy/espace-perso/demande-itdlc-it",
     *      name = "legacy_espace_perso_inge_itdlc"
     * )
     *
     * @param Request $request
     * @return null|RedirectResponse|Response
     * @throws \Exception
     */
    public function editIngeITDLCAction(Request $request)
    {
        $user = $this->getUser();

        // Stock return path in session and redirect to login if user is anonymous
        if (!is_object($user) || !$user instanceof UserInterface) {
            $this->session->set('_return', base64_encode($this->generateUrl($request->get('_route'), $request->get('_route_params'), UrlGeneratorInterface::ABSOLUTE_URL)));

            return $this->redirectToRoute('fos_user_security_login');
        }

        if (UserType::ENGINEER !== $user->getType()) {
            $this->addFlash('error', $this->translator->trans(
                'notice.user.access_denied',
                [],
                'notice'
            ));
            return new RedirectResponse($this->generateUrl('espace_perso'));
        }

        $form = $this->createForm(IngeDemandeITDLCType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $event = new FormEvent($form, $request);
            $this->dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);

            $this->userManager->updateUser($user);

            $this->itdlcMailer->confirmDemande($user);

            if (null === $response = $event->getResponse()) {
                $subject = 'Venez visiter le site cgenial.org';
                $body = str_replace("\n", '%0D%0A', // Required for line break representation in the mailto: URL scheme
                    $this->renderView('Front/Mail/invitation.html.twig', array(
                        'firstname' => $user->getFirstname(),
                        'lastname' => $user->getLastname(),
                    ))
                );

                $this->addFlash('info', '<div class="confirm"><span style="font-weight: bold;">Nous vous confirmons votre demande de participation à l’action Ingenieurs et techniciens dans les classes.</span><br/><br/>
                Nous nous efforçons d’y faire suite au plus vite.<br/>
                <a class="btn btn-mailto" href="mailto:?subject='.$subject.'&body='.$body.'">Invitez vos amis à visiter notre site en 1 clic !</a></div>');

                $url = $this->generateUrl('espace_perso');
                $response = new RedirectResponse($url);
            }

            $this->dispatcher->dispatch(
                FOSUserEvents::PROFILE_EDIT_COMPLETED,
                new FilterUserResponseEvent($user, $request, $response)
            );

            return $response;
        }

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

    /**
     * Ajout d'une disponibilité pour une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/legacy/espace-perso/availability/add/{ope}/{typedispo}",
     *      requirements = {"typedispo": "precis|hebdo"},
     *      name = "legacy_espace_perso_availability_add"
     * )
     *
     * @param Request $request
     * @param OperationITDLC $ope
     * @param string $typedispo
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function addAvailabilityAction(Request $request, OperationITDLC $ope, $typedispo)
    {
        $user = $this->getUser();

        if (UserType::TEACHER !== $user->getType()) {
            throw $this->createAccessDeniedException();
        }

        // Formulaire 
        $availability = new Availability;
        $form = $this->createForm(
            'precis' == $typedispo ? AvailabilityPrecisType::class : AvailabilityHebdoType::class,
            $availability, [
                'action' => $this->generateUrl('espace_perso_availability_add', [
                    'ope' => $ope->getId(),
                    'typedispo' => $typedispo
                ])
            ]
        );
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $availability->setOperationitdlc($ope);

            $this->em->persist($availability);
            $this->em->flush();

            $this->addFlash('success', 'Disponibilité ajoutée');

            return $this->redirectToRoute('espace_perso_prof_itdlc_edit', [
                'ope' => $ope->getId(),
            ]);
        }

        return $this->render('Front/Demande/availability.html.twig', array(
            'availability' => $availability,
            'form' => $form->createView(),
            'typedispo' => $typedispo,
        ));
    }

    /**
     * Modification d'une disponibilité d'une demande ITDLC d'un professeur
     *
     * @Route(
     *      "/legacy/espace-perso/availability/edit/{availability}",
     *      name = "legacy_espace_perso_availability_edit"
     * )
     *
     * @param Request $request
     * @param Availability $availability
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function editAvailabilityAction(Request $request, Availability $availability)
    {
        $user = $this->getUser();

        if (UserType::TEACHER !== $user->getType()) {
            throw $this->createAccessDeniedException();
        }

        $form = $this->createForm(
            $availability->getDateVisite() ? AvailabilityPrecisType::class : AvailabilityHebdoType::class,
            $availability
        );
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->em->persist($availability);
            $this->em->flush();

            $this->addFlash('success', 'Disponibilité modifiée');

            return $this->redirectToRoute('espace_perso_availability_edit', array(
                'availability' => $availability->getId(),
            ));
        }

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