<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Persistence\ManagerRegistry;

use App\Entity\Slide;
use App\Form\SlideType;

class SlideController extends AbstractController
{
    private $nameentity  = 'Slide';
    private $labelentity = 'App\Entity\Slide';
    private $labelroute  = 'app_portal_config_slide';
    private $labeldata   = 'slide';
    private $labeldatas  = 'slides';

    public function list($idpage,$idwidget,$access="config",Request $request, ManagerRegistry $em)
    {
        $usage=$request->query->get('usage');
        $group=$request->query->get('group');

        // On s'assure que le widget existe
        $pagewidget = $em->getRepository("App\Entity\Pagewidget")->find($idwidget);
        if (!$pagewidget) throw $this->createNotFoundException('Unable to find entity.');

        // Vérifier que l'on générer un slide
        if($access=="user") {
            if($usage=="user") {
                $user=$pagewidget->getPage()->getUser();
                if($user!=$this->getUser())  throw $this->createNotFoundException('Permission denied');
            }
            else {
                $groupentity=$em->getRepository("App\Entity\Group")->find($group);
                $usergroup=$em->getRepository("App\Entity\UserGroup")->findoneby(["user"=>$this->getUser(),"group"=>$groupentity]);
                if(!$usergroup||$usergroup->getRolegroup()<50) throw $this->createNotFoundException('Permission denied');
            }
        }
        
        // Recherche des slides du widget
        $datas = $em->getRepository($this->labelentity)->findBy(["pagewidget"=>$idwidget],["roworder"=>"ASC","title"=>"ASC"]);

      	return $this->render($this->nameentity.'\list.html.twig',[
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"), 
            'maxwidth'          => ($access=="user"),        
            'access'            => $access,
            'idpage'            => $idpage,
            'idwidget'          => $idwidget,
            'usage'             => $usage,
            'group'             => $group,
            $this->labeldatas   => $datas
        ]);
    }

    public function submit($idpage,$idwidget,$access="config",Request $request, ManagerRegistry $em)
    {
        $usage=$request->query->get('usage');
        $group=$request->query->get('group');

        // Initialisation de l'enregistrement
        $data = new Slide();
        $data->setRoworder(0);

        // On s'assure que le widget existe
        $pagewidget = $em->getRepository("App\Entity\Pagewidget")->find($idwidget);
        if (!$pagewidget) throw $this->createNotFoundException('Unable to find entity.');

        // Vérifier que l'on générer un slide
        if($access=="user") {
            if($usage=="user") {
                $user=$pagewidget->getPage()->getUser();
                if($user!=$this->getUser())  throw $this->createNotFoundException('Permission denied');
            }
            else {
                $groupentity=$em->getRepository("App\Entity\Group")->find($group);
                $usergroup=$em->getRepository("App\Entity\UserGroup")->findoneby(["user"=>$this->getUser(),"group"=>$groupentity]);
                if(!$usergroup||$usergroup->getRolegroup()<50) throw $this->createNotFoundException('Permission denied');
            }
        }

        // Création du formulaire
        $form = $this->createForm(SlideType::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();  
            $data->setPagewidget($pagewidget);           

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

            // Retour à la page
            return $this->redirect($this->generateUrl('app_portal_'.$access.'_slide_list',["idpage"=>$idpage,"idwidget"=>$idwidget,"usage"=>$usage,"group"=>$group]));
        }
        
        return $this->render($this->nameentity.'\edit.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),  
            'maxwidth'          => ($access=="user"),                   
            'entity'            => $data,
            'mode'              => "submit",
            'access'            => $access,   
            'idpage'            => $idpage,    
            'idwidget'          => $idwidget,
            'usage'             => $usage,
            'group'             => $group,
            'form'              => $form->createView(),
        ]);
    }  

    public function update($idpage,$id,$access="config",Request $request, ManagerRegistry $em)
    {
        $usage=$request->query->get('usage');
        $group=$request->query->get('group');

        // Récupération de l'enregistrement courant 
        $data=$this->getData($em,$id);
        if (!$data) throw $this->createNotFoundException('Unable to find entity.');

        // Vérifier que cet enregistrement est modifiable
        if($access=="user") {
            if($usage=="user") {
                $user=$data->getPagewidget()->getPage()->getUser();
                if($user!=$this->getUser())  throw $this->createNotFoundException('Permission denied');
            }
            else {
                $groupentity=$em->getRepository("App\Entity\Group")->find($group);
                $usergroup=$em->getRepository("App\Entity\UserGroup")->findoneby(["user"=>$this->getUser(),"group"=>$groupentity]);
                if(!$usergroup||$usergroup->getRolegroup()<50) throw $this->createNotFoundException('Permission denied');
            }
        }

        // Création du formulaire
        $form = $this->createForm(SlideType::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();

            // Retour à la page
            return $this->redirect($this->generateUrl('app_portal_'.$access.'_slide_list',["idpage"=>$idpage,"idwidget"=>$data->getPagewidget()->getId(),"usage"=>$usage,"group"=>$group]));
        }
        
       
        // Affichage du formulaire
        return $this->render($this->nameentity.'\edit.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),    
            'maxwidth'          => ($access=="user"),                 
            'entity'            => $data,
            'mode'              => "update",
            'access'            => $access,   
            'idpage'            => $idpage,    
            'idwidget'          => $data->getPagewidget()->getId(),     
            'usage'             => $usage,
            'group'             => $group,
            'form'              => $form->createView(),
        ]);
    }

    public function delete($idpage,$id,$access="config",Request $request, ManagerRegistry $em)
    {
        $usage=$request->query->get('usage');
        $group=$request->query->get('group');

        // Récupération de l'enregistrement courant 
        $data=$this->getData($em,$id);
        if (!$data) throw $this->createNotFoundException('Unable to find entity.');

        // Vérifier que cet enregistrement est supprimable
        if($access=="user") {
            if($usage=="user") {
                $user=$data->getPagewidget()->getPage()->getUser();
                if($user!=$this->getUser())  throw $this->createNotFoundException('Permission denied');
            }
            else {
                $groupentity=$em->getRepository("App\Entity\Group")->find($group);
                $usergroup=$em->getRepository("App\Entity\UserGroup")->findoneby(["user"=>$this->getUser(),"group"=>$groupentity]);
                if(!$usergroup||$usergroup->getRolegroup()<50) throw $this->createNotFoundException('Permission denied');
            }
        }
        
        // Widget encours
        $idwidget = $data->getPagewidget()->getId();

        // Supprimer la donnée
        $em->getManager()->remove($data);
        $em->getManager()->flush();
        
        // Retour à la page
        return $this->redirect($this->generateUrl('app_portal_'.$access.'_slide_list',["idpage"=>$idpage,"idwidget"=>$idwidget,"usage"=>$usage,"group"=>$group]));
    }

    public function upload($access="config")
    {
        return $this->render($this->nameentity.'\upload.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'access'        => $access
        ]);
    }

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