<?php

namespace Cadoles\PortalBundle\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 Doctrine\Common\Collections\Criteria;

use Cadoles\PortalBundle\Entity\Notice;
use Cadoles\PortalBundle\Form\NoticeType;

class NoticeController extends Controller
{
    private $labelroute  = 'cadoles_portal_config_notice';
    private $labelentity = 'CadolesPortalBundle:Notice';
    private $labeldata   = 'notice';
    private $labeldatas  = 'notices';

    public function listAction()
    {
        $notices = $this->getDoctrine()->getRepository($this->labelentity)->findAll();        
        $groups = $this->getDoctrine()->getRepository('CadolesCoreBundle:Group')->findBy([], ['label' => 'asc']);

        return $this->render($this->labelentity.':list.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,            
            'notices'           => $notices,
            'groups'            => $groups
        ]);
    }

    public function ajaxseleclistAction(Request $request)
    {
        // S'assurer que c'est un appel ajax
        if (!$request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Interdit'), 400);
        }

        $output=array();
        $em = $this->getDoctrine()->getManager();
        $page_limit=$request->query->get('page_limit');
        $q=$request->query->get('q');
        
        $qb = $em->createQueryBuilder();
        $qb->select('table')->from("CadolesPortalBundle:Notice",'table')
           ->where('table.title LIKE :value')
           ->setParameter("value", "%".$q."%")
           ->orderBy('table.title');
        
        $datas=$qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult();
        foreach($datas as $data) {
            array_push($output,array("id"=>$data->getId(),"text"=>$data->getTitle()));
        }

        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');      
        return $response;
    } 

    public function submitAction(Request $request)
    {
        // Initialisation de l'enregistrement
        $data = new Notice();
        
        // Création du formulaire
        $form = $this->createForm(NoticeType::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',
            'icons'             => $this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findAll(),
            '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(NoticeType::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

        // Supprimer la donnée
        $em = $this->getDoctrine()->getManager();
        $em->remove($data);
        $em->flush();
        
        return $this->redirectToRoute($this->labelroute);
    }

    public function usersAction($id)
    {
        $notice = $this->getData($id);        

        return $this->render($this->labelentity.':users.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,            
            'notice'            => $notice,
        ]);
    }    

    public function usersdeleteAction($id,$userid)
    {
        $notice = $this->getData($id);      
        
        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository("CadolesCoreBundle:User")->find($userid);
        $notice->removeUser($user);
        $em->flush();

        return $this->render($this->labelentity.':users.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,            
            'notice'            => $notice,
        ]);
    } 

    public function usersdeleteallAction($id)
    {
        $notice = $this->getData($id);  

        $em = $this->getDoctrine()->getManager();
        foreach($notice->getUsers() as $user) {
            $notice->removeUser($user);
        }
        $em->flush();
        return $this->render($this->labelentity.':users.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,            
            'notice'            => $notice,
        ]);
    }

    public function havereadAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $user=$this->getUser();
        $notices=$em->getRepository("CadolesPortalBundle:Notice")->getNoticeToRead($user);
            
        // Récupération redirection potentielle
        $id = $request->get('id');

        foreach($notices as $notice) {
            $users=$notice->getUsers();

            $userCriteria = Criteria::create()->where(Criteria::expr()->eq('id', $user->getId())); 
            $userCollection = $notice->getUsers()->matching($userCriteria);

            if($userCollection->isEmpty()) {
                $notice->addUser($user);
                $em->persist($notice);
                $em->flush();
            }
        }

        return $this->redirectToRoute("cadoles_core_home",["id"=>$id]);
    }

    public function viewAction(Request $request) {
        $em = $this->getDoctrine()->getManager();
        $user=$this->getUser();
        $notices=$em->getRepository("CadolesPortalBundle:Notice")->getNoticeUser($user,false);

        return $this->render('CadolesPortalBundle:Notice:view.html.twig',[
            'useheader'     => true,
            'usemenu'       => false,
            'usesidebar'    => false,  
            'maxwidth'      => true,
            'notices'       => $notices,
        ]);
    }

    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!="delete") {
            if(is_null($data->getDescription())) {
                $form->addError(new FormError('Description obligatoire'));
            }
        }

        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());
            }
        }
    }    
}
