<?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\Blogarticle;
use App\Form\BlogarticleType;

class BlogarticleController extends AbstractController
{
    private $nameentity="Blogarticle";
    private $labelentity="App\Entity\Blogarticle";
    private $routeprimary="app_portal_config_blogarticle";

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

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

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

    public function submit($idblog,$access="config", Request $request, ManagerRegistry $em)
    {
        $entity = new Blogarticle();
        $blog=$em->getRepository("App\Entity\Blog")->find($idblog);
        if($blog) $entity->setBlog($blog);
        
        $pageid=$request->get("page");
        if($pageid) {
            $page=$em->getRepository("App\Entity\Page")->find($pageid);
            $groups=$page->getGroups();
            $idgroup=$groups[0]->getId();
        }

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

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

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

            foreach($entity->getBlog()->getGroups() as $group) {
                if($group->getFgcanshare()) {
                    $url=$this->generateUrl('app_core_redirect', ['route'=>'app_portal_user_blogarticle_view','id'=>$entity->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
                    $message="Création article<br><a href='$url' target='_top'>".$entity->getName()."</a>";
                    $this->wss->addMessage($this->getUser()->getApikey(),$group->getId(),$message);
                }
            }

            if(is_null($pageid))
                return $this->redirect($this->generateUrl('app_portal_'.$access.'_blogarticle_view',["id"=>$entity->getId()]));          
            else
                return $this->redirect($this->generateUrl('app_portal_'.$access.'_page_view',["id"=>$pageid,"usage"=>"group","group"=>$idgroup]));          
        }

        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(),
            'pageid'            => $pageid
        ]);
    }

    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\Blog")->getPermission($this->getUser(),$entity->getBlog(),$cansee,$canupdate,$canadd);
            if(!$canadd) throw $this->createNotFoundException('Permission denied');
            elseif(!$canupdate&&$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->getBlog()->getGroups() as $group) {
                if($group->getFgcanshare()) {
                    $url=$this->generateUrl('app_core_redirect', ['route'=>'app_portal_user_blogarticle_view','id'=>$entity->getId()], UrlGeneratorInterface::ABSOLUTE_URL);
                    $message="Modification article<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.'_blogarticle_view',["id"=>$entity->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.');
        
        $idblog=$entity->getBlog()->getId();

        // On s'assure que l'utilisateur à la permission de supprimer
        if($access=="user") {
            $em->getRepository("App\Entity\Blog")->getPermission($this->getUser(),$entity->getBlog(),$cansee,$canupdate,$canadd);
            if(!$canadd) throw $this->createNotFoundException('Permission denied');
            elseif(!$canupdate&&$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.'_blog_view',["id"=>$idblog]));
    }

    public function view($id, $access="config", Request $request, ManagerRegistry $em)
    {
        $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 blog
        $groups=$entity->getBlog()->getGroups();
        $idpage=null;
        $idgroup=null;
        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;

            $blogs=$em->getRepository("App\Entity\Blog")->findBy(["id"=>$entity->getBlog()->getId()]);
        }
        else {
            // On récupère l'ensemble des blogs de l'utilisateur
            $em->getRepository("App\Entity\Blog")->getBlogsUser($user,$blogsuser,$blogsadmin,$blogsshared);
            $blogs=array_merge($blogsuser,$blogsadmin->toArray(),$blogsshared);

            // permission
            if($id==0) {
                $cansee=true;
                $canadd=true;
            }
            else {
                $em->getRepository("App\Entity\Blog")->getPermission($user,$entity->getBlog(),$cansee,$canupdate,$canadd);
                if(!$canupdate&&$this->getUser()==$entity->getUser()) $canupdate=true;                
            }
          
            if(!$cansee) throw $this->createNotFoundException('Permission denied');
        }

        $em->getRepository("App\Entity\Blogarticle")->getBlogsArticles($blogs,0,10,$count,$blogarticles);

        return $this->render($this->nameentity.'\view.html.twig', [
            'useheader'         => ($access=="config"),
            'usemenu'           => false,
            'usesidebar'        => ($access=="config"),  
            'maxwidth'          => ($access=="user"),
            'entity'            => $entity,
            'access'            => $access,
            'canupdate'         => $canupdate,
            'canadd'            => $canadd,
            'blogs'             => $blogs,
            'blogarticles'      => $blogarticles,
            'idpage'            => $idpage,
            'idgroup'           => $idgroup,
        ]);

    }

    public function upload($access=null, Request $request, ManagerRegistry $em) {
        // 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));

    }       

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

}
