<?php

namespace Cadoles\PortalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\Common\Collections\ArrayCollection;
use Ramsey\Uuid\Uuid;

use Cadoles\PortalBundle\Entity\Project;
use Cadoles\PortalBundle\Form\ProjectType;
use Cadoles\PortalBundle\Form\ProjectShareType;
use Cadoles\PortalBundle\Form\ProjectWriterType;

class ProjectController extends Controller
{
    private $labelentity="CadolesPortalBundle:Project";
    private $routeprimary="cadoles_portal_config_project";

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

    public function ajaxlistAction(Request $request,$access="config")
    {
        // 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');
        $alluser= $request->query->get('alluser');

        // On sauvegarde en session le flag alluser
        $this->get("session")->set("alluserproject",$alluser);

        // Query de base
        $qbase=$em->createQueryBuilder()->from($this->labelentity,'table');
        $qsearch=$em->createQueryBuilder()->from($this->labelentity,'table');

        if($alluser=="false") {
            $qbase->where("table.user is null");
            $qsearch->where("table.user is null");
        }
        else {
            $qbase->from('CadolesCoreBundle:User','user')
                  ->where("table.user=user");

            $qsearch->from('CadolesCoreBundle:User','user')
                    ->where("table.user=user");
        }           

        if($alluser=="false") 
            $qsearch->andwhere('table.id LIKE :value OR table.name LIKE :value');
        else
            $qsearch->andWhere('table.id LIKE :value OR table.name LIKE :value OR user.username LIKE :value') ;  

        $qsearch->setParameter("value", "%".$search["value"]."%");

        // Nombre total d'enregistrement
        $total = $qbase->select('COUNT(table)')->getQuery()->getSingleScalarResult();

        // Nombre d'enregistrement filtré
        if($search["value"]=="")
            $totalf = $total;
        else {
            $totalf= $qsearch->select('COUNT(table)')->getQuery()->getSingleScalarResult();
        }

        // Parcours des Enregistrement
        if($search["value"]=="")
            $qb = $qbase->select('table');
        else
            $qb = $qsearch->select('table');

        // Order
        switch($order[0]["column"]) {
            case 1 : 
            $qb->orderBy('table.name',$order[0]["dir"]);
            break;
            case 2 : 
            if($alluser=="true") $qb->orderBy('user.username',$order[0]["dir"]);
            break;            
        }

        // Execution de la requete d'affichage
        $datas=$qb->setFirstResult($start)->setMaxResults($length)->getQuery()->getResult();
        //dump($qsearch->getQuery()->getSql());

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

        foreach($datas as $data) {
            $route=str_replace("_config_","_".$access."_",$this->routeprimary);
            $action = "";
            $action.="<a href='".$this->generateUrl($route.'_update', array('id'=>$data->getId()))."' title='Configurer'><i class='fa fa-cog fa-fw fa-2x'></i></a>";
            $action.="<a href='".$this->generateUrl($route.'_view', array('id'=>$data->getId()))."' title='Afficher'><i class='fa fa-eye fa-fw fa-2x'></i></a>";
            $action.="<a href='".$this->generateUrl($route.'_delete', array('id'=>$data->getId()))."' data-method='delete' title='Supprimer'><i class='fa fa-trash fa-fw fa-2x'></i></a>";
            

            $user="";
            if($data->getUser()) {
                $user.="<img src='/".$this->container->getParameter('alias')."/uploads/avatar/".$data->getUser()->getAvatar()."' class='avatar' style='margin:0px 5px 0px 0px;display:inline-block;'>";
                $user.=$data->getUser()->getUsername();
            }            

            array_push($output["data"],array($action,$data->getName(),$user));
        }

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

    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:Project",'table')
           ->where('table.name LIKE :value')
           ->setParameter("value", "%".$q."%")
           ->orderBy('table.name');
        
        $datas=$qb->setFirstResult(0)->setMaxResults($page_limit)->getQuery()->getResult();
        foreach($datas as $data) {
            array_push($output,array("id"=>$data->getId(),"text"=>$data->getName()));
        }

        $response = new Response(json_encode($output));    
        $response->headers->set('Content-Type', 'application/json');      
        return $response;
    }
    
    private function entityForm(Project $entity,$access="config")
    {
        $route=str_replace("_config_","_".$access."_",$this->routeprimary);

        if ($this->getDoctrine()->getManager()->contains($entity)) {
            return $this->createForm(ProjectType::class, $entity, [
                "mode"   => "update",
                "access" => $access
            ]);
        }
        else {
            return $this->createForm(ProjectType::class, $entity, [
                "mode"   => "submit",
                "access" => $access
            ]);
        }
    }

    public function submitAction(Request $request,$access="config")
    {
        if($access=="user"&&!$this->get('session')->get('cancreateproject'))
            throw $this->createNotFoundException('Permission denied');

        $entity = new Project();

        $form   = $this->entityForm($entity,$access);
        $form->handleRequest($request);

        if ($form->isValid()) {

            
            $em = $this->getDoctrine()->getManager();
            if($access=="user") $entity->setUser($this->getUser());

            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_project_view',["id"=>$entity->getId()]));          
        }

        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),   
            'maxwidth'          => ($access=="user"),           
            'entity'            => $entity,
            'mode'              => "submit",
            'access'            => $access,
            'form'              => $form->createView()
        ]);
    }

    public function updateAction(Request $request, $id,$access="config")
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository($this->labelentity)->find($id);
        if (!$entity) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission de modifier
        if($access=="user") {
            $em->getRepository($this->labelentity)->getPermission($this->getUser(),$entity,$cansee,$canupdate,$canadd);
            if(!$canupdate) throw $this->createNotFoundException('Permission denied');
        }            
        
        // Création du formulaire
        $form = $this->entityForm($entity,$access);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_project_view',["id"=>$entity->getId()]));          
        }


        return $this->render($this->labelentity.':edit.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),  
            'maxwidth'          => ($access=="user"),                  
            'entity'            => $entity,
            'access'            => $access,
            'mode'              => "update",
            'form'              => $form->createView(),
        ]);
    }

    public function shareAction(Request $request, $id,$access="config")
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository($this->labelentity)->find($id);
        if (!$entity) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission de modifier
        if($access=="user") {
            $em->getRepository($this->labelentity)->getPermission($this->getUser(),$entity,$cansee,$canupdate,$canadd);
            if(!$canupdate) throw $this->createNotFoundException('Permission denied');
        }            
        
        // Création du formulaire
        $form = $this->createForm(ProjectShareType::class, $entity, ["access" => $access, "user" => $this->getUser()]);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_project_view',["id"=>$id]));
        }


        return $this->render($this->labelentity.':share.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),    
            'maxwidth'          => ($access=="user"),
            'entity'            => $entity,
            'access'            => $access,
            'form'              => $form->createView(),
        ]);
    }

    public function writerAction(Request $request, $id,$access="config")
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $em->getRepository($this->labelentity)->find($id);
        if (!$entity) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission de modifier
        if($access=="user") {
            $em->getRepository($this->labelentity)->getPermission($this->getUser(),$entity,$cansee,$canupdate,$canadd);
            if(!$canupdate) throw $this->createNotFoundException('Permission denied');
        }            
        
        // Création du formulaire
        $form = $this->createForm(ProjectWriterType::class, $entity, ["id"=>$entity->getId(),"access" => $access, "user" => $this->getUser()]);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_project_view',["id"=>$id]));
        }


        return $this->render($this->labelentity.':writer.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),    
            'maxwidth'          => ($access=="user"),
            'entity'            => $entity,
            'access'            => $access,
            'form'              => $form->createView(),
        ]);
    }

    public function deleteAction(Request $request, $id,$access="config")
    {
        $em = $this->getDoctrine()->getManager();
        $entity = $this->getDoctrine()->getRepository($this->labelentity)->find($id);
        if (!$entity) throw $this->createNotFoundException('Unable to find entity.');
    
        // On s'assure que l'utilisateur à la permission de supprimer
        if($access=="user") {
            $em->getRepository($this->labelentity)->getPermission($this->getUser(),$entity,$cansee,$canupdate,$canadd);
            if(!$canupdate) throw $this->createNotFoundException('Permission denied');
        }

        // Suppression
        $em->remove($entity);
        $em->flush();

        // Retour
        if($access=="config")
            return $this->redirect($this->generateUrl($this->routeprimary));
        else   
            return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_project_view'));
    }

    public function viewAction(Request $request, $id, $access="config") {

        $page=$request->query->get("page");
        if(is_null($page)) $page=1;

        $em = $this->getDoctrine()->getManager();
        $entity=[];
        if($id!=0) {
            $entity = $em->getRepository($this->labelentity)->find($id);
            if (!$entity) throw $this->createNotFoundException('Unable to find entity.');
        }

        // On recherche la premiere page associé au groupe du projet
        $idpage=null;
        $idgroup=null;
        if($id!=0) {
            $groups=$entity->getGroups();
            if($groups[0]) {
                if($groups[0]->getFgcanshare()) {
                    $pages=$groups[0]->getPages();
                    if($pages[0]) {
                        $idpage=$pages[0]->getId();
                        $groups=$pages[0]->getGroups();
                        $idgroup=$groups[0]->getId();
                    }                        
                }
            }
        }
        
        // Permissions
        $user=$this->getUser();
        if($access=="config") {
            $canupdate = true;
            $canadd=true;
            $cansee=true;

            $projects=$em->getRepository($this->labelentity)->findBy(["id"=>$id]);
            $entity->setCanupdate(true);
            $entity->setCanadd(true);
            
        }
        else {
            // On récupère l'ensemble des projects de l'utilisateur
            $em->getRepository($this->labelentity)->getProjectsUser($user,$projectsuser,$projectsadmin,$projectsshared);
            $projects=array_merge($projectsuser,$projectsadmin->toArray(),$projectsshared);

            // Utilisateur sans project = creation d'un project par défaut
            if(empty($projectsuser)&&$user) {
                $project=new Project();
                $project->setName("Mon Project");
                $project->setUser($user);
                $project->setCanupdate(true);
                $em->persist($project);
                $em->flush();

                $projectsuser=[$project];
            }

            // permission
            if($id==0) {
                $cansee=true;
                $canadd=($this->getUser());
            }
            else {
                $em->getRepository($this->labelentity)->getPermission($user,$entity,$cansee,$canupdate,$canadd);
            }
          
            if(!$cansee) throw $this->createNotFoundException('Permission denied');
            $canupdate=$this->get('session')->get('cancreateproject');
        }

        $pagination=15;
        if($entity)
            $em->getRepository("CadolesPortalBundle:Projecttask")->getProjectsTasks($entity,($page-1)*$pagination,$pagination,$count,$projecttasks);
        else
            $em->getRepository("CadolesPortalBundle:Projecttask")->getProjectsTasks($projects,($page-1)*$pagination,$pagination,$count,$projecttasks);

            
        return $this->render($this->labelentity.':view.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),  
            'maxwidth'          => ($access=="user"),
            'entity'            => $entity,
            'access'            => $access,
            'canupdate'         => $canupdate,
            'canadd'            => $cansee,
            'projecttasks'      => $projecttasks,
            'projects'          => $projects,
            'countarticles'     => $count,
            'pagination'        => $pagination,
            'page'              => $page,
            'idpage'            => $idpage,
            'idgroup'           => $idgroup
        ]);

    }
}
