<?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 Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

use Cadoles\PortalBundle\Entity\Projectcomment;
use Cadoles\PortalBundle\Form\ProjectcommentType;
use Cadoles\CoreBundle\Entity\Usergroup;

class ProjectcommentController extends Controller
{
    private $labelentity="CadolesPortalBundle:Projectcomment";
    private $routeprimary="cadoles_portal_config_projectcomment";

    private function entityForm(Projectcomment $entity,$access="config")
    {
        $route=str_replace("_config_","_".$access."_",$this->routeprimary);

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

    public function submitAction(Request $request,$idtask,$access="config")
    {
        $em = $this->getDoctrine()->getManager();
        $entity = new Projectcomment();
        $projecttask=$em->getRepository("CadolesPortalBundle:Projecttask")->find($idtask);
        if($projecttask) $entity->setProjecttask($projecttask);
        $entity->setName("Commentaire");
        
        $form   = $this->entityForm($entity,$access);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $entity->setUser($this->getUser());
            $entity->setSubmit(new \Datetime());

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

            foreach($entity->getProjecttask()->getProject()->getGroups() as $group) {
                if($group->getFgcanshare()) {
                    $url=$this->generateUrl('cadoles_core_redirect', ['route'=>'cadoles_portal_user_projecttask_view','id'=>$entity->getProjecttask()->getId()], UrlGeneratorInterface::ABSOLUTE_URL);

                    $message="Création commentaire tâche<br><a href='$url' target='_top'>".$entity->getName()."</a>";
                    $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);
                    }
                }
            }

            return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_projecttask_view',["id"=>$entity->getProjecttask()->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("CadolesPortalBundle:Project")->getPermission($this->getUser(),$entity->getProjecttask()->getProject(),$cansee,$canupdate,$canadd);
            if(!$canadd&&$this->getUser()!=$entity->getUser()) 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();

            foreach($entity->getProjecttask()->getProject()->getGroups() as $group) {
                if($group->getFgcanshare()) {
                    $url=$this->generateUrl('cadoles_core_redirect', ['route'=>'cadoles_portal_user_projecttask_view','id'=>$entity->getProjecttask()->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
                    $message="Modification commentaire tâche<br><a href='$url' target='_top'>".$entity->getProjecttask()->getName()."</a>";
                    $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);
                    }
                }
            }

            return $this->redirect($this->generateUrl('cadoles_portal_'.$access.'_projecttask_view',["id"=>$entity->getProjecttask()->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 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.');
        
        $idtask=$entity->getProjecttask()->getId();

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

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

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

    public function uploadAction(Request $request,$access=null) {
        // Fichier temporaire uploadé
        $tmpfile    = $request->files->get('upload');
        $extention  = $tmpfile->getClientOriginalExtension();

        // Répertoire de Destination
        $fs         = new Filesystem();
        $rootdir    = $this->get('kernel')->getRootDir()."/../web";
        $fs->mkdir($rootdir."/uploads/ckeditor");
        
        // Fichier cible
        $targetName = uniqid().".".$extention;
        $targetFile = $rootdir."/uploads/ckeditor/".$targetName;
        $targetUrl  = "/".$this->getParameter('alias')."/uploads/ckeditor/".$targetName;
        $message    = "";

        move_uploaded_file($tmpfile,$targetFile);
        
        $output["uploaded"]=1;
        $output["fileName"]=$targetName;
        $output["url"]=$targetUrl;

        return new Response(json_encode($output));

    }    

    public function imageAction($access="config")
    {
        return $this->render('CadolesPortalBundle:Projecttask:image.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'access'        => $access
        ]);
    }    
}
