<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpKernel\KernelInterface;

use App\Entity\Flux;
use App\Form\FluxType;

class FluxController extends AbstractController
{
    private $nameentity  = 'Flux';
    private $labelentity = 'App\Entity\Flux';
    private $labelroute  = 'app_portal_config_flux';
    private $labeldata   = 'flux';
    private $labeldatas  = 'fluxs';

    private $appKernel;
    
    public function __construct(KernelInterface $appKernel)
    {
        $this->appKernel = $appKernel;
    }


    public function list(ManagerRegistry $em)
    {
        $fluxs = $em->getRepository($this->labelentity)->findBy([], ['rowOrder' => 'asc']);        
        $groups = $em->getRepository('App\Entity\Group')->findBy([], ['label' => 'asc']);

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

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

        $output=array();
        $page_limit=$request->query->get('page_limit');
        $q=$request->query->get('q');
        
        $qb = $em->getManager()->createQueryBuilder();
        $qb->select('table')->from("App\Entity\Flux",'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 submit(Request $request,ManagerRegistry $em)
    {
        // Initialisation de l'enregistrement
        $data = new Flux();
        $data->setMaxread(5);
        
        // Création du formulaire
        $form = $this->createForm(FluxType::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();  

            // Sauvegarde
            $em->getManager()->persist($data);
            $em->getManager()->flush();

            // Retour à la liste
            return $this->redirectToRoute($this->labelroute);
        }
        
        // Affichage du formulaire
        return $this->render($this->nameentity.'\edit.html.twig', [
            'useheader'         => true,
            'usemenu'           => false,
            'usesidebar'        => true,            
            $this->labeldata    => $data,
            'mode'              => 'submit',
            'icons'             => $em->getRepository("App\Entity\Icon")->findAll(),
            'form'              => $form->createView()
        ]);
    }  

    public function update($id,Request $request,ManagerRegistry $em)
    {
        // Récupération de l'enregistrement courant 
        $data=$this->getData($em,$id);
        
        // Vérifier que cet enregistrement est modifiable
                                    
        // Création du formulaire
        $form = $this->createForm(FluxType::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()) {
            $data = $form->getData();

            // Sauvegarde
            $em->getManager()->flush();

            // On supprime le potentiel cache de ce flux
            $dir = $this->appKernel->getProjectDir().'/uploads/flux/';
            $mask = $dir."flux-*".$data->getId().".*";
            array_map( "unlink", glob( $mask ) );

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

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

        // Vérifier que cet enregistrement est supprimable

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

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

        $output=array();
        $id=$request->request->get('id');
        $order=$request->request->get('order');
        
        $entity = $em->getRepository($this->labelentity)->find($id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find entity.');
        }

        $entity->setRoworder($order);
        $em->getManager()->flush();

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

    protected function getDatas($em)
    {
        $datas = $em->getRepository($this->labelentity)->findAll();
        return $datas;
    } 
            
    protected function getData($em,$id)
    {
        $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()) {
            $errors = $form->getErrors();
            foreach( $errors as $error ) {
                $request->getSession()->getFlashBag()->add("error", $error->getMessage());
            }
        }
    }    
}
