<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpKernel\KernelInterface;

use App\Service\MessageService;
use App\Entity\Projectcomment;
use App\Form\ProjectcommentType;

class ProjectcommentController extends AbstractController
{
    private $nameentity="Projectcomment";
    private $labelentity="App\Entity\Projectcomment";
    private $routeprimary="app_portal_config_projectcomment";

    private $appKernel;
    private $wss;
    
    public function __construct(KernelInterface $appKernel, messageService $wss)
    {
        $this->appKernel = $appKernel;
        $this->wss = $wss;
    }

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

        if ($em->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 submit($idtask, $access="config", Request $request, ManagerRegistry $em)
    {
        $entity = new Projectcomment();
        $projecttask=$em->getRepository("App\Entity\Projecttask")->find($idtask);
        if($projecttask) $entity->setProjecttask($projecttask);
        $entity->setName("Commentaire");
        
        $form   = $this->entityForm($access,$entity,$em);
        $form->handleRequest($request);

        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $entity->setUser($this->getUser());
            $entity->setSubmit(new \Datetime());

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

            foreach($entity->getProjecttask()->getProject()->getGroups() as $group) {
                if($group->getFgcanshare()) {
                    $url=$this->generateUrl('app_core_redirect', ['route'=>'app_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>";
                    $this->wss->addMessage($this->getUser()->getApikey(),$group->getId(),$message);
                }
            }

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

        return $this->render($this->nameentity.'\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 update($id, $access="config", Request $request, ManagerRegistry $em)
    {
        $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("App\Entity\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($access,$entity,$em);
        $form->handleRequest($request);

        if ($form->get('submit')->isClicked() && $form->isValid()) {
            $em->getManager()->flush();

            foreach($entity->getProjecttask()->getProject()->getGroups() as $group) {
                if($group->getFgcanshare()) {
                    $url=$this->generateUrl('app_core_redirect', ['route'=>'app_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>";
                    $this->wss->addMessage($this->getUser()->getApikey(),$group->getId(),$message);
                }
            }

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


        return $this->render($this->nameentity.'\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 delete($id, $access="config", Request $request, ManagerRegistry $em)
    {
        $entity = $em->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("App\Entity\Project")->getPermission($this->getUser(),$entity->getProjecttask()->getProject(),$cansee,$canupdate,$canadd);
            if(!$canadd&&$this->getUser()!=$entity->getUser()) throw $this->createNotFoundException('Permission denied');
        }

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

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

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

        // Répertoire de Destination
        $fs         = new Filesystem();
        $rootdir    = $this->appKernel->getProjectDir()."/public";
        $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));

    }    
  
}
