<?php

namespace Cadoles\CoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;

use Cadoles\CoreBundle\Entity\Whitelist;
use Cadoles\CoreBundle\Form\WhitelistType;

class WhitelistController extends Controller
{
    private $labelroute  = 'cadoles_core_config_whitelist';
    private $labelentity = 'CadolesCoreBundle:Whitelist';
    private $labeldata   = 'whitelist';
    private $labeldatas  = 'whitelists';

    public function listAction()
    {
      	return $this->render('CadolesCoreBundle:Whitelist:list.html.twig',[
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,                 
        ]);
    }

    public function ajaxlistAction(Request $request)
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        
        $em = $this->getDoctrine()->getManager();
        
        $start=$request->query->get('start');
        $length= $request->query->get('length');
        $search= $request->query->get('search');
        $draw= $request->query->get('draw');
        $order= $request->query->get('order');
      
        // Nombre total d'enregistrement
        $total = $em->createQueryBuilder()->select('COUNT(table)')->from($this->labelentity,'table')->getQuery()->getSingleScalarResult();

        // Nombre d'enregistrement filtré
        if($search["value"]=="")
            $totalf = $total;
        else {
            $totalf= $em->createQueryBuilder()
                        ->select('COUNT(table)')
                        ->from($this->labelentity,'table')
                        ->where('table.label LIKE :value')
                        ->setParameter("value", "%".$search["value"]."%")
                        ->getQuery()
                        ->getSingleScalarResult();
        }

        // Construction du tableau de retour
        $output = array(
            'draw' => $draw,
            'recordsFiltered' => $totalf,
            'recordsTotal' => $total,
            'data' => array(),
        );

        // Parcours des Enregistrement
        $qb = $em->createQueryBuilder();
        $qb->select('table')->from($this->labelentity,'table');
        if($search["value"]!="") {
            $qb ->where('table.label LIKE :value')
                ->setParameter("value", "%".$search["value"]."%");
        }
        switch($order[0]["column"]) {
            case 1 : 
            $qb->orderBy('table.label',$order[0]["dir"]);
            break;
        }

        $datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();

        foreach($datas as $data) {
            $action ="<a href='".$this->generateUrl('cadoles_core_config_whitelist_update', array('id'=>$data->getId()))."' title='Modifier'><i class='fa fa-file fa-fw fa-2x'></i></a>";
            $action.="<a href='".$this->generateUrl('cadoles_core_config_whitelist_delete', array('id'=>$data->getId()))."' title='Supprimer'><i class='fa fa-trash fa-fw fa-2x'></i></a>";
            array_push($output["data"],array($action,$data->getLabel()));
        }

        // Retour
        return new Response(json_encode($output), 200);
    }    

    public function submitAction(Request $request)
    {
        // Initialisation de l'enregistrement
        $data = new Whitelist();
        
        // Création du formulaire
        $form = $this->createForm(WhitelistType::class,$data,array("mode"=>"submit"));

        // Récupération des data du formulaire
        $form->handleRequest($request);
        
        // Sur erreur
        $this->getErrorForm(null,$form,$request,$data,"submit");
        
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {  
            $data = $form->getData();  
            $em = $this->getDoctrine()->getManager();
            
            // Sauvegarde
            $em->persist($data);
            $em->flush();

            // Retour à la liste
            return $this->redirectToRoute($this->labelroute);
        }
        
        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,                 
            $this->labeldata    => $data,
            'mode'              => 'submit',
            'form'              => $form->createView()
        ]);
    }  

    public function updateAction($id,Request $request)
    {
        // Récupération de l'enregistrement courant 
        $data=$this->getData($id);
        
        // Vérifier que cet enregistrement est modifiable
                                    
        // Création du formulaire
        $form = $this->createForm(WhitelistType::class,$data,array("mode"=>"update"));

        // Récupération des data du formulaire
        $form->handleRequest($request);
    
        // Sur erreur
        $this->getErrorForm($id,$form,$request,$data,"update");
        
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $data = $form->getData();
            
            // Sauvegarde
            $em->persist($data);
            $em->flush();

            // Retour à la liste
            return $this->redirectToRoute($this->labelroute);
        }
        
       
        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,                 
            $this->labeldata    => $data,
            'mode'              => 'update',
            'form'              => $form->createView()
        ]);
    }

    public function deleteAction($id,Request $request)
    {
        // Récupération de l'enregistrement courant 
        $data=$this->getData($id);

        // Vérifier que cet enregistrement est supprimable

        // Création du formulaire
        $form = $this->createForm(WhitelistType::class,$data,array("mode"=>"delete"));

        // Récupération des data du formulaire
        $form->handleRequest($request);        

        // Sur erreur
        $this->getErrorForm($id,$form,$request,$data,"delete");
                
        // Sur validation
        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($data);
            $em->flush();
            
            return $this->redirectToRoute($this->labelroute);
        }
        
        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,                 
            $this->labeldata    => $data,
            'mode'              => 'delete',
            'form'              => $form->createView()
        ]);                    
    }

    public function ajaxiswhitelistAction(Request $request)
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }
        $email=$request->request->get('email');
        $email=explode("@",$email);
        $domaine=end($email);

        // Rechercher le mail dans la liste blanche
        $em = $this->getDoctrine()->getManager();
        $whitelist=$em->getRepository($this->labelentity)->findOneBy(["label"=>$domaine]);
        if($whitelist)
            return new Response("OK", 200);
        else
            return new Response("KO", 200);
    }

    protected function getDatas()
    {
        $em = $this->getDoctrine()->getManager();
        $datas = $em->getRepository($this->labelentity)->findAll();
        return $datas;
    } 
            
    protected function getData($id)
    {
        $em = $this->getDoctrine()->getManager();
        $data = $em->getRepository($this->labelentity)->find($id);

        if (!$data) {
            throw $this->createNotFoundException('Unable to find '.$this->labeldata);
        }

        return $data;
    } 

    protected function getErrorForm($id,$form,$request,$data,$mode) {
        if ($form->get('submit')->isClicked()&&$mode=="delete") {
        }

        if ($form->get('submit')->isClicked() && $mode=="submit") {
        }

        if ($form->get('submit')->isClicked() && !$form->isValid()) {
            $this->get('session')->getFlashBag()->clear();
            $validator = $this->get('validator');
            $errors = $validator->validate($data);
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }

            $errors = $form->getErrors();
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }
        }
    }    
}
