<?php

namespace Cadoles\PortalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\File\File;

use Doctrine\Common\Collections\ArrayCollection;
use Ramsey\Uuid\Uuid;

use Cadoles\PortalBundle\Entity\Calendarevent;
use Cadoles\PortalBundle\Form\CalendareventShareType;

class CalendareventController extends Controller
{
    private $labelentity="CadolesPortalBundle:Calendarevent";
    private $routeprimary="cadoles_portal_config_calendarevent";

    public function loadAction(Request $request,$access="config")
    {
        // S'assurer que c'est un appel ajax
        // if (!$request->isXmlHttpRequest()) return new JsonResponse(array('message' => 'Interdit'), 400);
        
        $events=array();
        $eventids=array();
        $idcalendar     = $request->query->get('idcalendar');
        $start          = $request->query->get('start');
        $end            = $request->query->get('end');


        // On charge un et un seul calendrier
        if($idcalendar>0) {
            $em = $this->getDoctrine()->getManager();
            $calendar = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendar")->find($idcalendar);
            if (!$calendar) throw $this->createNotFoundException('Unable to find entity.');
            if($access=="config")
                $calendar->setCanupdate(true);
            else {
                $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendar")->getPermission($this->getUser(),$calendar,$cansee,$canupdate,$canadd);
                if(!$cansee) throw $this->createNotFoundException('Permission denied');
                $calendar->setCanupdate($canupdate);
                $calendar->setCanadd($canadd);
            }

            $calendars=[$calendar];
        }
        // Sinon on charge l'ensemble des calendriers associé au profil
        else {
            $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendar")->getCalendarsUser($this->getUser(),$calendarssuser,$calendarsadmin,$calendarsshared);
            $calendars=array_merge($calendarssuser,$calendarsadmin->toArray(),$calendarsshared);
        }

        // On recherche des event partagés
        foreach($calendars as $calendar) {
            $calendarevents = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendarevent")->getCalendareventByDate($calendar,$start,$end);

            foreach($calendarevents as $calendarevent) {
                $tmp=[];
                $tmp['id']            = strval($calendarevent->getId());
                $tmp['title']         = $calendarevent->getName();
                $tmp['description']   = $calendarevent->getDescription();
                $tmp['start']         = $calendarevent->getStart()->format("Y-m-d\TH:i:s");
                $tmp['end']           = $calendarevent->getEnd()->format("Y-m-d\TH:i:s");
                $tmp['color']         = "#".(is_null($calendar->getColor())?$this->get('session')->get('color')["main"]:$calendar->getColor());
                $tmp['allDay']        = $calendarevent->getAllday();
                $tmp['calendar']      = $calendar->getId();
                $tmp['editable']      = $calendarevent->getCalendar()->getCanadd();
                $tmp['files']         = $this->loadpj($tmp['id'] );

                array_push($events,$tmp);
                array_push($eventids,$tmp["id"]);
            }

            // On recherche les taches associées aux groupes du calendrier
            if($this->getUser()) {
                $groups=$calendar->getGroups();
                foreach($groups as $group) {
                    $projects=$group->getProjects();
                    foreach($projects as $project) {
                        $projecttasks = $this->getDoctrine()->getRepository("CadolesPortalBundle:Projecttask")->getProjectTasksByDate($project,$this->getUser(),$start,$end);
                        foreach($projecttasks as $projecttask) {
                            $tmp=[];
                            $tmp['id']            = "TASK".strval($projecttask->getId());
                            $tmp['title']         = "TACHE = ".$projecttask->getName();
                            $tmp['description']   = $projecttask->getDescription();
                            $tmp['start']         = $projecttask->getEnd()->format("Y-m-d\TH:i:s");
                            $tmp['end']           = $projecttask->getEnd()->format("Y-m-d\TH:i:s");
                            $tmp['color']         = "#".$this->get('session')->get('color')["main"];
                            $tmp['allDay']        = true;
                            $tmp['calendar']      = $project->getId();
                            $tmp['name']          = $project->getName()." - Tache";
                            $tmp['editable']      = false;
                               
                            array_push($events,$tmp);
                            array_push($eventids,$tmp["id"]);
                        }
                    }
                }
            }
        }

        // On récupére les évenement partagé de l'utilisateur
        if($this->getUser()) {
            $calendarevents = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendarevent")->getCalendareventGroupsShareByDate($this->getUser(),$start,$end);
            
            foreach($calendarevents as $calendarevent) {
                if($idcalendar>0) {
                    if(!$calendarevent->getGroups()->contains($calendar->getGroups()[0])) continue;
                }

                $tmp=[];
                $tmp['id']            = strval($calendarevent->getId());
                $tmp['title']         = $calendarevent->getName();
                $tmp['description']   = $calendarevent->getDescription();
                $tmp['start']         = $calendarevent->getStart()->format("Y-m-d\TH:i:s");
                $tmp['end']           = $calendarevent->getEnd()->format("Y-m-d\TH:i:s");
                $tmp['color']         = "#".(is_null($calendar->getColor())?$this->get('session')->get('color')["main"]:$calendar->getColor());
                $tmp['allDay']        = $calendarevent->getAllday();
                $tmp['calendar']      = $calendar->getId();
                $tmp['editable']      = $calendarevent->getCalendar()->getCanupdate();
                $tmp['files']         = $this->loadpj($tmp['id'] );

                if(!in_array($tmp['id'],$eventids)) {
                    array_push($events,$tmp);
                    array_push($eventids,$tmp["id"]);
                }
            }
        }

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

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

        $output=array();
        $idcalendar     = $request->request->get('idcalendar');
        $title          = $request->request->get('title');
        $description    = $request->request->get('description');
        $start          = new \DateTime($request->request->get('start'));
        $end            = new \DateTime($request->request->get('end'));
        $allday         = ($request->request->get('allday')=="true");

        $em = $this->getDoctrine()->getManager();
        $calendar = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendar")->find($idcalendar);
        if (!$calendar) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission de supprimer
        if($access=="user") {
            $em->getRepository("CadolesPortalBundle:Calendar")->getPermission($this->getUser(),$calendar,$cansee,$canupdate,$canadd);
            if(!$canadd) throw $this->createNotFoundException('Permission denied');
        }        

        $calendarevent=new Calendarevent();
        $calendarevent->setCalendar($calendar);
        $calendarevent->setName($title);
        $calendarevent->setDescription($description);
        $calendarevent->setStart($start);
        $calendarevent->setEnd($end);
        $calendarevent->setAllday($allday);

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

        foreach($calendarevent->getCalendar()->getGroups() as $group) {
            if($group->getFgcanshare()) {
                $message="Création évènement<br>".$calendarevent->getName()."<br>du ".$start->format("d/m/Y H:i")." au ".$end->sub(new \DateInterval('PT1M'))->format("d/m/Y H:i");
                $usergroup=$em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$group,"user"=>$this->getUser()]);
                if($usergroup) {
                    $key=$usergroup->getKeyvalue();
                    $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($key,$this->getUser()->getId(),$group->getId(),$message);
                }
            }
        }

        $output["id"]=$calendarevent->getId();
        $output["color"]="#".(is_null($calendar->getColor())?$this->get('session')->get('color')["main"]:$calendar->getColor());

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

    public function updateAction(Request $request, $access="config")
    {
        // 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');
        $idcalendar     = $request->request->get('idcalendar');
        $title          = $request->request->get('title');
        $description    = $request->request->get('description');
        $start          = new \DateTime($request->request->get('start'));
        $end            = new \DateTime($request->request->get('end'));
        $allday         = ($request->request->get('allday')=="true");

        $em = $this->getDoctrine()->getManager();
        $calendar = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendar")->find($idcalendar);
        if (!$calendar) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission
        if($access=="user") {
            $em->getRepository("CadolesPortalBundle:Calendar")->getPermission($this->getUser(),$calendar,$cansee,$canupdate,$canadd);
            if(!$canadd) throw $this->createNotFoundException('Permission denied');
        }        

        $calendarevent = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendarevent")->find($id);
        if (!$calendarevent) throw $this->createNotFoundException('Unable to find entity.');

        $calendarevent->setCalendar($calendar);
        $calendarevent->setName($title);
        $calendarevent->setDescription($description);
        $calendarevent->setStart($start);
        $calendarevent->setEnd($end);
        $calendarevent->setAllday($allday);

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

        foreach($calendarevent->getCalendar()->getGroups() as $group) {
            if($group->getFgcanshare()) {
                $message="Modification évènement<br>".$calendarevent->getName()."<br>du ".$start->format("d/m/Y H:i")." au ".$end->sub(new \DateInterval('PT1M'))->format("d/m/Y H:i");
                $usergroup=$em->getRepository("CadolesCoreBundle:Usergroup")->findOneBy(["group"=>$group,"user"=>$this->getUser()]);
                if($usergroup) {
                    $key=$usergroup->getKeyvalue();
                    $websocket = $this->container->get('cadoles.websocket.pushmessage')->send($key,$this->getUser()->getId(),$group->getId(),$message);
                }
            }
        }

        $output["id"]=$calendarevent->getId();
        $output["color"]="#".(is_null($calendar->getColor())?$this->get('session')->get('color')["main"]:$calendar->getColor());

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



    public function deleteAction(Request $request, $access="config")
    {
        // 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');
        $idcalendar     = $request->request->get('idcalendar');
        $title          = $request->request->get('title');
        $description    = $request->request->get('description');
        $start          = new \DateTime($request->request->get('start'));
        $end            = new \DateTime($request->request->get('end'));
        $allday         = ($request->request->get('allday')=="true");

        $em = $this->getDoctrine()->getManager();
        $calendar = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendar")->find($idcalendar);
        if (!$calendar) throw $this->createNotFoundException('Unable to find entity.');

        // On s'assure que l'utilisateur à la permission
        if($access=="user") {
            $em->getRepository("CadolesPortalBundle:Calendar")->getPermission($this->getUser(),$calendar,$cansee,$canupdate,$canadd);
            if(!$canadd) throw $this->createNotFoundException('Permission denied');
        }        

        $calendarevent = $this->getDoctrine()->getRepository("CadolesPortalBundle:Calendarevent")->find($id);
        if (!$calendarevent) throw $this->createNotFoundException('Unable to find entity.');

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

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

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

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

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

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


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

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

        // On s'assure que l'utilisateur à la permission
        if($access=="user") {
            $em->getRepository("CadolesPortalBundle:Calendar")->getPermission($this->getUser(),$calendar,$cansee,$canupdate,$canadd);
            if(!$canadd) throw $this->createNotFoundException('Permission denied');
        }  

        $files = $this->loadpj($id);

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

    private function loadpj($id) {
        $directory=$this->get('kernel')->getRootDir()."/../uploads/file/calendarevent-".$id;
        $files=[];
        $fs = new Filesystem();
        if($fs->exists($directory)) {
            $finder = new Finder();
            $finder->sortByName()->in($directory)->exclude('thumb')->exclude('thumbmini');
            foreach ($finder as $file) {
                $tmpfile=[];
                $tmpfile["name"]=$file->getRelativePathname();
                $tmpfile["extension"]=strtolower($file->getExtension());
                $fileinfo = new file($file->getPathname());
                $tmpfile["minetype"]=$fileinfo->getMimeType();
                $tmpfile["minefamily"]=explode("/",$tmpfile["minetype"])[0];

                $tmpfile["thumb"]="";
                if($tmpfile["extension"]=="pdf") {
                    $tmpfile["thumb"]="/".$this->getParameter('alias')."/bundles/cadolescore/images/files/".$tmpfile["extension"].".png";
                }
                elseif($fs->exists($directory."/thumbmini/".$tmpfile["name"])) {
                    $data = file_get_contents($directory."/thumbmini/".$tmpfile["name"]);
                    $tmpfile["thumb"]="data:image/" . $tmpfile["extension"] . ";base64," . base64_encode($data);
                }
                elseif($fs->exists($directory."/thumb/".$tmpfile["name"])) {
                    $data = file_get_contents($directory."/thumb/".$tmpfile["name"]);
                    $tmpfile["thumb"]="data:image/" . $tmpfile["extension"] . ";base64," . base64_encode($data);
                }
                elseif($fs->exists($this->get('kernel')->getRootDir()."/../web/bundles/cadolescore/images/files/".$tmpfile["extension"].".png")) {
                    $tmpfile["thumb"]="/".$this->getParameter('alias')."/bundles/cadolescore/images/files/".$tmpfile["extension"].".png";
                }

                array_push($files,$tmpfile);
            }                        
        }        

        return $files;
    }
}
