<?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 Cadoles\PortalBundle\Entity\Icon;
use Cadoles\PortalBundle\Form\IconType;

class IconController extends Controller
{
    private $labelroute  = 'cadoles_portal_config_icon';
    private $labelentity = 'CadolesPortalBundle:Icon';
    private $labeldata   = 'icon';
    private $labeldatas  = 'icons';

    public function listAction(Request $request,$access="config")
    {
        $inframe=$request->get("inframe");

        $em = $this->getDoctrine()->getManager();
        if($access=="config")
            $icons=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>null]);
        else
            $icons=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>$this->getUser()]);

      	return $this->render($this->labelentity.':list.html.twig',[
            'useheader'         => !($inframe),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"&&!$inframe),   
            'access'            => $access,
            $this->labeldatas   => $icons,
            'inframe'           => $inframe
        ]);
    }

    public function submitAction(Request $request,$access="config")
    {
        $inframe=$request->get("inframe");

        // Initialisation de l'enregistrement
        $data = new Icon();
        
        // Création du formulaire
        $form = $this->createForm(IconType::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();  
            if($access=="user") $data->setUser($this->getUser());

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

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

    public function updateAction($id,Request $request,$access="config")
    {
        $inframe=$request->get("inframe");

        // 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(IconType::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('cadoles_portal_'.$access.'_icon',['inframe'=>$inframe]);
        }
        
       
        // Affichage du formulaire
        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => !($inframe),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"&&!$inframe),   
            'access'            => $access,         
            $this->labeldata    => $data,
            'mode'              => 'update',
            'form'              => $form->createView(),
            'refresh'           => false,
            'inframe'           => $inframe
        ]);
    }

    public function deleteAction($id,Request $request,$access="config")
    {
        $inframe=$request->get("inframe");

        // 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('cadoles_portal_'.$access.'_icon',['inframe'=>$inframe]);
    }

    public function selectAction($access="config") {
        // Affichage du formulaire
        $icons=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>null]);
        $iconsuser=null;
        if($access=="user") $iconsuser=$this->getDoctrine()->getRepository("CadolesPortalBundle:Icon")->findBy(["user"=>$this->getUser()]);

        return $this->render($this->labelentity.':select.html.twig',[
            'useheader'           => false,
            'usemenu'           => false,
            'usesidebar'        => false,   
            'access'            => $access,
            $this->labeldatas   => $icons,
            'iconsuser'         => $iconsuser
        ]);

    }

    public function iconAction()
    {
        return $this->render('CadolesPortalBundle:Icon:icon.html.twig',[
            'useheader'         => false,
            'usemenu'           => false,
            'usesidebar'        => false,            
        ]);
    }

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