<?php
namespace AppBundle\Utils\EventListener;

use AppBundle\Entity\Company;
use AppBundle\Utils\Event\AdminEvents;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\RedirectResponse;

class RegistrationListener implements EventSubscriberInterface
{

    protected $em;
    protected $slugService;
    protected $security;
    protected $router;

    public function __construct($em, $slugService, $security, $router, $userManager)
    {
        $this->em = $em;
        $this->slugService = $slugService;
        $this->security = $security;
        $this->router = $router;
        $this->userManager = $userManager;
    }

    public static function getSubscribedEvents()
    {
        return array(
            FOSUserEvents::REGISTRATION_SUCCESS => 'setUserRoles',
            FOSUserEvents::SECURITY_IMPLICIT_LOGIN => 'createCompanyUser',
            AdminEvents::ADMIN_USER_CREATE => 'createCompanyUser',
        );
    }

    public function setUserRoles(FormEvent $event)
    {
        $user = $event->getForm()->getData();
        $roleInput = $event->getForm()->get("role")->getData();
        $rolesArr = null;
        switch ($roleInput) {
            case 'TALENT':
                $user->addRole('ROLE_USER');
                $user->addRole('ROLE_TALENT');
                break;
            case 'COMPANY':
                $user->addRole('ROLE_USER');
                $user->addRole('ROLE_COMPANY');
                break;
        }
        $session = new Session();
        if ($session->get('registration_destination')) {
            $userConnected = $this->security->getToken()->getUser();
            $this->em->persist($user);
            $this->assignToRealAccount($userConnected, $user);
            $redirection = $session->get('registration_destination');
            $response = new RedirectResponse($redirection);
            $event->setResponse($response);
        }
    }

    public function assignToRealAccount($userConnected, $existingUser) {
        $answers = $this->em->getRepository('AppBundle:Answer')->findBy(array('user' => $userConnected));
        $medias = $this->em->getRepository('AppBundle:Media')->findBy(array('creator'=> $userConnected));
        foreach ($medias as $key => $media) {
            $media->setCreator($existingUser);
        }
        $this->em->flush();
        foreach ($answers as $key => $answer) {
            $answer->setUser($existingUser);
        }
        $this->em->flush();
        $this->userManager->deleteUser($userConnected);
    }

    public function redirectUser(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();
        $roles = $user->getRoles();
        if (in_array('ROLE_TALENT', $roles, true)) {
            $redirection = $this->router->generate('talent_dashboard');
        } elseif (in_array('ROLE_COMPANY', $roles, true)) {
            $redirection = $this->router->generate('company_dashboard');
        } elseif (in_array('ROLE_TERRITORY', $roles, true)) {
            $redirection = $this->router->generate('territory_dashboard');
        } else {
            $redirection = $this->router->generate('homepage');
        }
        $response = $event->getResponse();
        $response->setTargetUrl($redirection);
    }

    public function createCompanyUser($event)
    {

        $slugService = $this->slugService;
        $user = $event->getUser();
        if ($user->getCompany() == null) {
            $company = new Company();
            $alias = $slugService->slugify($user->getId() . "-" . $user->getFirstname() . "-" . $user->getLastname());
            $company->setAlias($alias);
            if ($user->hasRole('ROLE_TALENT')) {
                $company->setType("TALENT");
            } elseif ($user->hasRole('ROLE_COMPANY')) {
                $company->setType("COMPANY");
            } elseif ($user->hasRole('ROLE_TERRITORY')) {
                $company->setType("TERRITORY");
            } else {
                return false;
            }
            $user->setCompany($company);
            $this->em->persist($user);
            $this->em->flush();
        }
    }
}