<?php

namespace UserBundle\Controller;

use FOS\UserBundle\Controller\RegistrationController as BaseController;
use FOS\UserBundle\Event\FilterUserResponseEvent;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\Form\Factory\FactoryInterface;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;



 class RegistrationController extends BaseController
{
 public function registerAction(Request $request)
    {
            //die();
        $em = $this->get('doctrine')->getManager();
        /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
        $formFactory = $this->get('fos_user.registration.form.factory');
        /** @var $userManager \FOS\UserBundle\Model\UserManagerInterface */
        $userManager = $this->get('fos_user.user_manager');
        /** @var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
        $dispatcher = $this->get('event_dispatcher');
// die();
        $user = $userManager->createUser();

        $country = $this->getUser()->getPays();
        $country = $em->getRepository('AppBundle:Pays')->findOneById($country->getId());
        $user->setEnabled(false);
        $user->setCreatedAt( new \DateTime());

        $event = new GetResponseUserEvent($user, $request);
        $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

        if (null !== $event->getResponse()) {
            return $event->getResponse();
        }

        $form = $formFactory->createForm();
         if(in_array('ROLE_SUPER_ADMIN', $this->getUser()->getRoles())){
            $rolesArray = [
                'TECHNICIEN' => 'ROLE_TECH',
                'PARTENAIRE' => 'ROLE_PARTENAIRE',
                'ADMIN' => 'ROLE_ADMIN',
                'SUPER_ADMIN' => 'ROLE_SUPER_ADMIN'
            ];
            $listepays = $em->getRepository('AppBundle:Pays')->findBy([], ['nom'=>'ASC']);
        }else{
            $listepays = array($country);
            $rolesArray = [
                'TECHNICIEN' => 'ROLE_TECH',
                'PARTENAIRE' => 'ROLE_PARTENAIRE'
            ];
            // $form->add('pays', EntityType::class, array('data' => $country,'class' => "AppBundle\Entity\Pays", 'label'=>'nom', 'required' => true,  'query_builder' => function ($er) use ( $country ) {
            //         return $er->createQueryBuilder('p')
            //                 ->where('p.id = :pays')
            //                 ->setParameters('pays', $country->getId())
            //                 ->orderBy('p.nom', 'ASC');
            //     }))
            // ;
        }
        $form
            ->add('pays', EntityType::class, array('data' => $country,'class' => "AppBundle\Entity\Pays", 'label'=>'nom', 'required' => true, 'choices' => $listepays))
            ->add('roles', ChoiceType::class, [
                'required' => false,
                'multiple' => false,
                'mapped' => false,
                'choices'  => $rolesArray,
                'attr' => array(
                    'size' => 1
                ),
                'choice_attr' => function($choice, $key, $value) {
                    return ['class' => 'attending_'.strtolower($key)];
                }
            ])
        ;
        $form->setData($user);

        $form->handleRequest($request);

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

            $userManager->updateUser($user);

            if (null === $response = $event->getResponse()) {
                $url = $this->generateUrl('fos_user_registration_confirmed');
                $response = new RedirectResponse($url);
            }

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

            return $response;
        }

        return $this->render('FOSUserBundle:Registration:register.html.twig', array(
            'form' => $form->createView(),
        ));
    }


}










// /**
//  * Registration controller.
//  *
//  * @Route("admin/member")
//  */




// class RegistrationController extends BaseController
// {
//     public function registerAction(Request $request)
//         {
//             //die('/');
//             /** @var $formFactory FactoryInterface */
//             $formFactory = $this->get('fos_user.registration.form.factory');
//             /* @var $userManager UserManagerInterface  */
//             $userManager = $this->get('fos_user.user_manager');
//             /** @var $dispatcher EventDispatcherInterface */
//             $dispatcher = $this->get('event_dispatcher');

//             // $formFactory->add('pays', EntityType::class, array('class' => "AppBundle\Entity\Pays", 'label'=>'nom', 'required'=>true,'query_builder' => function ($er) {
//             //         return $er->createQueryBuilder('p')
//             //                 ->orderBy('p.nom', 'ASC');
//             //     }));
//             $em = $this->get('doctrine')->getManager();
//             $user = $userManager->createUser();
            
//             $country = $this->getUser()->getPays();
//             $country = $em->getRepository('AppBundle:Pays')->findOneById($country->getId());
//             // dump($country);
//             $event = new GetResponseUserEvent($user, $request);
//             $dispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

//             if (null !== $event->getResponse()) {
//                 return $event->getResponse();
//             }
//             // dump($user->getRoles());
//             $form = $formFactory->createForm();

//             if(in_array('ROLE_SUPER_ADMIN', $this->getUser()->getRoles())){
//                 $rolesArray = [
//                     'TECHNICIEN' => 'ROLE_TECH',
//                     'PARTENAIRE' => 'ROLE_PARTENAIRE',
//                     'ADMIN' => 'ROLE_ADMIN',
//                     'SUPER_ADMIN' => 'ROLE_SUPER_ADMIN'
//                 ];
//                 $listepays = $em->getRepository('AppBundle:Pays')->findBy([], ['nom'=>'ASC']);
//             }else{
//                 $listepays = array($country);
//                 $rolesArray = [
//                     'TECHNICIEN' => 'ROLE_TECH',
//                     'PARTENAIRE' => 'ROLE_PARTENAIRE'
//                 ];
//                 // die();
//                 // $form->add('pays', EntityType::class, array('data' => $country,'class' => "AppBundle\Entity\Pays", 'label'=>'nom', 'required' => true,  'query_builder' => function ($er) use ( $country ) {
//                 //         return $er->createQueryBuilder('p')
//                 //                 ->where('p.id = :pays')
//                 //                 ->setParameters('pays', $country->getId())
//                 //                 ->orderBy('p.nom', 'ASC');
//                 //     }))
//                 // ;
//             }
//             $form
//                 ->add('pays', EntityType::class, array('data' => $country,'class' => "AppBundle\Entity\Pays", 'label'=>'nom', 'required' => true, 'choices' => $listepays))
//                 ->add('roles', ChoiceType::class, [
//                     'required' => false,
//                     'multiple' => false,
//                     'mapped' => false,
//                     'choices'  => $rolesArray,
//                     'attr' => array(
//                         'size' => 1
//                     ),
//                     'choice_attr' => function($choice, $key, $value) {
//                         return ['class' => 'attending_'.strtolower($key)];
//                     }
//                 ])
//             ;

//             $user->setPlainPassword("sunusante2050");
//             $user->setUsername("email.com");     
//             $user->setPays($this->getUser()->getPays());
//             // $role = 'ROLE_USER';
//             // $roles = array();
//             // $user->setRoles($roles);
//             // $form->setData($user);
//             $form->handleRequest($request);
//             $roles = array($form->get('roles')->getData());
//             $user->setRoles( $roles );
//             if ($form->isSubmitted()) {
//                 $user->setPlainPassword("sunusante2050");
//                 $user->setUsername($form->get('email')->getData());            
//                 if ($form->isValid()) {
//                     $user->setEmail($form->get('email')->getData());
//                     $user->setEnabled(false);
//                     $user->setNom($form->get('nom')->getData());
//                     $user->setPrenom($form->get('prenom')->getData());
//                     $user->setTelephone($form->get('telephone')->getData());
//                     $user->setAdresse($form->get('adresse')->getData());
//                     $user->setCreatedAt(new \DateTime());
//                     $user->setCreatedBy($this->getUser());
//                     $user->setPays($form->get('pays')->getData());
//                     $event = new FormEvent($form, $request);
//                     $dispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

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

//                     /*****************************************************
//                      * Add new functionality (e.g. log the registration) *
//                      *****************************************************/
//                     // $this->container->get('logger')->info(
//                     // );
//                     $this->addFlash('success','Un mail a été envoyé a l\'adresse email de lutilisateur pour validation du compte');

//                     if (null === $response = $event->getResponse()) {
//                         $url = $this->generateUrl('app_user_registration');
//                         $response = new RedirectResponse($url);
//                     }
//                     return $this->redirectToRoute('app_user_registration');
//                     // $dispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
//                     // dump($response);
//                     // die('/');
//                     // return $response;
//                 }

//                 $event = new FormEvent($form, $request);
//                 $dispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);

//                 if (null !== $response = $event->getResponse()) {
//                     return $response;
//                 }
//             }

//             return $this->render('@FOSUser/Registration/register.html.twig', array(
//                 'form' => $form->createView(),
//             ));
//         }

// }


// class RegistrationController extends BaseController
// {
//     private $eventDispatcher;
//     private $formFactory;
//     private $userManager;
//     private $tokenStorage;

//     /**
//      * RegistrationController constructor.
//      */
//     public function __construct(EventDispatcherInterface $eventDispatcher, FactoryInterface $formFactory, UserManagerInterface $userManager, TokenStorageInterface $tokenStorage)
//     {
//         dump('Constuctor');die();
//         parent::__construct($eventDispatcher,$formFactory,$userManager,$tokenStorage);
//     }


//     /**
//      * @param Request $request
//      *
//      * @return Response
//      */
//     public function registerAction(Request $request)
//     {
//         dump();die();
//         $user = $this->userManager->createUser();
//         $user->setEnabled(false);

//         $event = new GetResponseUserEvent($user, $request);
//         $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_INITIALIZE, $event);

//         if (null !== $event->getResponse()) {
//             return $event->getResponse();
//         }

//         $form = $this->formFactory->createForm();
//         $form->setData($user);

//         $form->handleRequest($request);

//         if ($form->isSubmitted()) {
//             if ($form->isValid()) {
//                 $event = new FormEvent($form, $request);
//                 $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_SUCCESS, $event);

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

//                 if (null === $response = $event->getResponse()) {
//                     $url = $this->generateUrl('user_index');
//                     $response = new RedirectResponse($url);
//                 }

//                 $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_COMPLETED, new FilterUserResponseEvent($user, $request, $response));

//                 return $response;
//             }

//             $event = new FormEvent($form, $request);
//             $this->eventDispatcher->dispatch(FOSUserEvents::REGISTRATION_FAILURE, $event);

//             if (null !== $response = $event->getResponse()) {
//                 return $response;
//             }
//         }

//         return $this->render('@FOSUser/Registration/register.html.twig', array(
//             'form' => $form->createView(),
//         ));
//     }

// }
