<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Form\FormError;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\File\File;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\HttpKernel\KernelInterface;

use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class FileController extends AbstractController
{
    private $appKernel;
    
    public function __construct(KernelInterface $appKernel)
    {
        $this->appKernel = $appKernel;
    }

    public function list($directory, $access="config", Request $request, ManagerRegistry $em) {
        $canupdate= $this->getPermission($em,$access,$directory);
        $subdirectory=$request->get("subdirectory");
        $clear=$request->get("clear");
        $view=$request->get("view");
        $sort=$request->get("sort");
        $order=$request->get("order");
        $defaultview=$request->get("defaultview");

        // Récupérer les préférences utilisateur
        $toupdate=false;
        $preference=$this->getUser()->getPreference();
        if(is_null($preference)) $preference=[];
        
        // Préférence subdirectory
        if(!array_key_exists("widgetsubdirectory",$preference)) {
            $toupdate=true;
            $preference["widgetsubdirectory"]=[];
        }
        if((!array_key_exists($directory,$preference["widgetsubdirectory"]))) {
            $toupdate=true;
            $preference["widgetsubdirectory"][$directory]=null;
        }
        if($clear&&!is_null($preference["widgetsubdirectory"][$directory])) {
            $toupdate=true;
            $preference["widgetsubdirectory"][$directory]=null;
        }
        else {
            if(!$subdirectory) $subdirectory = $preference["widgetsubdirectory"][$directory];
            elseif($subdirectory!=$preference["widgetsubdirectory"][$directory]) {
                $toupdate=true;
                $preference["widgetsubdirectory"][$directory] = $subdirectory;
            }
        }

        // Préférence mode de visualisation
        if(!array_key_exists("widgetviewdirectory",$preference)) {
            $toupdate=true;
            $preference["widgetviewdirectory"]=[];
        }
        if((!array_key_exists($directory,$preference["widgetviewdirectory"]))) {
            $toupdate=true;
            $preference["widgetviewdirectory"][$directory]=$defaultview;
        }
        if($view&&$preference["widgetviewdirectory"][$directory]!=$view) {
            $toupdate=true;
            $preference["widgetviewdirectory"][$directory]=$view;            
        }

        // Préférence trie 
        if(!array_key_exists("widgetsortdirectory",$preference)) {
            $toupdate=true;
            $preference["widgetsortdirectory"]=[];
        }
        if((!array_key_exists($directory,$preference["widgetsortdirectory"]))) {
            $toupdate=true;
            $preference["widgetsortdirectory"][$directory]="name";
        }
        if($sort&&$preference["widgetsortdirectory"][$directory]!=$sort) {
            $toupdate=true;
            $preference["widgetsortdirectory"][$directory]=$sort;            
        }
       
        // Préférence order 
        if(!array_key_exists("widgetorderdirectory",$preference)) {
            $toupdate=true;
            $preference["widgetorderdirectory"]=[];
        }
        if((!array_key_exists($directory,$preference["widgetorderdirectory"]))) {
            $toupdate=true;
            $preference["widgetorderdirectory"][$directory]="SORT_ASC";
        }
        if($sort&&$preference["widgetorderdirectory"][$directory]!=$order) {
            $toupdate=true;
            $preference["widgetorderdirectory"][$directory]=$order;            
        }


        // Mise à jour des préferences
        if($toupdate) {
            $this->getUser()->setPreference($preference);
            $em->getManager()->flush();             
        }

        // Construire le chemin réel
        $iddirectory=explode("-",$directory)[1];
        $fulldirectory=$this->appKernel->getProjectDir()."/uploads/file/".$directory."/".$subdirectory;
        
        $parents=null;
        $dirname="Home";
        if($subdirectory) {
            $parents=explode("/",$subdirectory);
            $dirname=end($parents);
            array_pop($parents);
        }
        
        // Générer le tableau de fichiers
        $files=[];
        $dirs=[];
        $fs = new Filesystem();

        if($fs->exists($fulldirectory)) {
            $finder = new Finder();
            $finder->depth('== 0')->sortByName()->in($fulldirectory)->exclude('thumb')->exclude('thumbmini')->exclude('__trash');
            
            foreach ($finder as $file) {
                if(is_dir($file)) {
                    $tmp=[];
                    $tmp["name"]=$file->getRelativePathname();
                    $tmp["namesort"]=strtolower($tmp["name"]);
                    $tmp["date"]=date ("d/m/Y H:i", filemtime($file));
                    $tmp["datesort"] = date ("YmdHi", filemtime($file));
                    array_push($dirs,$tmp);
                }
                else {
                    $tmp=[];
                    $tmp["name"]=$file->getRelativePathname();
                    $tmp["namesort"]=strtolower($tmp["name"]);
                    $tmp["extension"]=strtolower($file->getExtension());
                    $fileinfo = new file($file->getPathname());
                    $tmp["minetype"]=$fileinfo->getMimeType();
                    $tmp["minefamily"]=explode("/",$tmp["minetype"])[0];
                    $tmp["date"] = date ("d/m/Y H:i", filemtime($file));
                    $tmp["datesort"] = date ("YmdHi", filemtime($file));

                    $tmp["thumb"]="";
                    if($tmp["extension"]=="pdf") {
                        $tmp["thumb"]="/".$this->getParameter('alias')."images/files/".$tmp["extension"].".png";                  
                    }
                    elseif($fs->exists($fulldirectory."/thumbmini/".$tmp["name"])) {
                        $data = file_get_contents($fulldirectory."/thumbmini/".$tmp["name"]);
                        $tmp["thumb"]="data:image/" . $tmp["extension"] . ";base64," . base64_encode($data);
                    }
                    elseif($fs->exists($fulldirectory."/thumb/".$tmp["name"])) {
                        $data = file_get_contents($fulldirectory."/thumb/".$tmp["name"]);
                        $tmp["thumb"]="data:image/" . $tmp["extension"] . ";base64," . base64_encode($data);
                    }
                    elseif($fs->exists($this->appKernel->getProjectDir()."/public/images/files/".$tmp["extension"].".png")) {
                        $tmp["thumb"]="/".$this->getParameter('alias')."images/files/".$tmp["extension"].".png";
                    }

                    array_push($files,$tmp);
                }
            }
        }

        // Flag poubelle
        $fgtrash=false;
        if(stripos($subdirectory,"_trash")==1) $fgtrash=true;

        // Trie du tableu
        $sort = array_column($files, $preference["widgetsortdirectory"][$directory]."sort");
        if($preference["widgetorderdirectory"][$directory]=="SORT_ASC")
            array_multisort($sort, SORT_ASC, $files);
        else 
            array_multisort($sort, SORT_DESC, $files);

        $sort = array_column($dirs, $preference["widgetsortdirectory"][$directory]."sort");
        if($preference["widgetorderdirectory"][$directory]=="SORT_ASC")
            array_multisort($sort, SORT_ASC, $dirs);
        else 
            array_multisort($sort, SORT_DESC, $dirs);        

        return $this->render('File\list.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'access'        => $access,
            'iddirectory'   => $iddirectory,
            'directory'     => $directory,
            'parents'       => $parents,
            'subdirectory'  => $subdirectory,
            'dirname'       => $dirname,
            'dirs'          => $dirs,
            'files'         => $files,
            'canupdate'     => $canupdate,
            'canadd'        => $canupdate,
            'view'          => $preference["widgetviewdirectory"][$directory],
            'sort'          => $preference["widgetsortdirectory"][$directory],
            'order'         => $preference["widgetorderdirectory"][$directory],
            'fgtrash'       => $fgtrash,
        ]);        
    }

    public function upload($id, $type, $access="config", Request $request, ManagerRegistry $em)
    {
        $canupdate =$this->getPermission($em,$access,$id);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');

        $subdirectory=urldecode($request->get("subdirectory"));
        $forcereload=(is_null($request->get("forcereload"))?true:$request->get("forcereload"));
        
        return $this->render('File\upload.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'access'        => $access,
            'id'            => $id,
            'type'          => $type,
            'subdirectory'  => $subdirectory,
            'forcereload'   => $forcereload,
        ]);
    }  

    public function subdirectory($id, $type, $access="config", Request $request, ManagerRegistry $em)
    {
        $canupdate =$this->getPermission($em,$access,$id);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');

        $subdirectory=$request->get("subdirectory");
        $defaultData = [];
        $form = $this->createFormBuilder()
                     ->add('subdirectory', TextType::class,["label"=>"Répertoire"])
                     ->add('submit', SubmitType::class,["label"=>"Valider"])
                     ->getForm();
        
        $form->handleRequest($request);
        $toclose=false;

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            if($data["subdirectory"]=="thumb"||$data["subdirectory"]=="thumbmini"||$data["subdirectory"]=="__trash") {
                $form->addError(new FormError('Nom de répertoire réservé, merci de choisir un autre nom de répertoire'));
                $this->get('session')->getFlashBag()->clear();
                $request->getSession()->getFlashBag()->add("error", 'Nom de répertoire réservé, merci de choisir un autre nom de répertoire');
            }
            else {
                $filesystem = new Filesystem();
                $fulldirectory=$this->appKernel->getProjectDir()."/uploads/file/".$id;
                if($subdirectory) $fulldirectory.="/".$subdirectory."/".$data["subdirectory"];
                else $fulldirectory.="/".$data["subdirectory"];
                $filesystem->mkdir($fulldirectory);
                $toclose=true;        
            }
        }

        return $this->render('File\subdirectory.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'access'        => $access,
            'id'            => $id,
            'type'          => $type,
            'subdirectory'  => $subdirectory,
            'form'          => $form->createView(),
            'toclose'       => $toclose,
        ]);
    }  

    public function rename($id, $oldname, $access="config", Request $request, ManagerRegistry $em)
    {
        $canupdate =$this->getPermission($em,$access,$id);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');

        $subdirectory=$request->get("subdirectory");

        $form = $this->createFormBuilder()
                     ->add('subdirectory', TextType::class,["label"=>"Renommer"])
                     ->add('submit', SubmitType::class,["label"=>"Valider"])
                     ->getForm();
        
        $form->handleRequest($request);
        $toclose=false;

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            if($data["subdirectory"]=="thumb"||$data["subdirectory"]=="thumbmini"||$data["subdirectory"]=="__trash") {
                $form->addError(new FormError('Nom réservé, merci de choisir un autre nom'));
                $this->get('session')->getFlashBag()->clear();
                $request->getSession()->getFlashBag()->add("error", 'Nom réservé, merci de choisir un autre nom');
            }
            else {
                $fs = new Filesystem();
                $fulldirectory=$this->appKernel->getProjectDir()."/uploads/file/".$id;
                if($subdirectory) $fulldirectory.="/".$subdirectory;
                
                $urlsource= $fulldirectory."/".$oldname;
                $urldestination = $fulldirectory."/".$data["subdirectory"];

                if($urlsource!=$urldestination) {
                    
                    if($fs->exists($urldestination)) {
                        $form->addError(new FormError('Ce nom existe déjà'));
                        $this->get('session')->getFlashBag()->clear();
                        $request->getSession()->getFlashBag()->add("error", 'Ce nom existe déjà');
                    }
                    elseif($fs->exists($urlsource)) {
                        if(is_dir($urlsource)) {
                            $fs->mirror($urlsource,$urldestination);
                            $fs->remove($urlsource);
                        }
                        else {
                            $fs->rename($urlsource,$urldestination,true);
                            $fs->touch($urldestination);

                            $urlsource= $fulldirectory."/thumb/".$oldname;
                            $urldestination = $fulldirectory."/thumb/".$data["subdirectory"];
                            if($fs->exists($urlsource))
                                $fs->rename($urlsource,$urldestination,true);

                            $urlsource= $fulldirectory."/thumbmini/".$oldname;
                            $urldestination = $fulldirectory."/thumbmini/".$data["subdirectory"];
                            if($fs->exists($urlsource))
                                $fs->rename($urlsource,$urldestination,true);
                        }
                        
                        $toclose=true; 
                    }
                }

                       
            }
        } else $form->get('subdirectory')->setData($oldname);

        return $this->render('File\subdirectory.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'access'        => $access,
            'id'            => $id,
            'subdirectory'  => $subdirectory,
            'form'          => $form->createView(),
            'toclose'       => $toclose,
        ]);
    } 

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

        $output=array();
        $directory=$request->request->get('directory');

        // Récupération du répertoire source et le nom du fichier
        $racine=$this->appKernel->getProjectDir()."/uploads/file";
        $directory=$request->request->get('directory');
        $dirsource  =$request->request->get('subdirectory');
        $namesource =$request->request->get('filename');

        $canupdate =$this->getPermission($em,$access,$directory);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');

        $fs = new Filesystem();

        // Déplacer le fichier
        $urlsource=$racine."/".$directory."/".$dirsource."/".$namesource;
        $urldestination=$racine."/".$directory."/__trash/".$dirsource."/".$namesource;
        $fs->mkdir($racine."/".$directory."/__trash/".$dirsource);
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else $fs->rename($urlsource,$urldestination,true);

        }

        // Déplacer le thumb
        $fs->mkdir($racine."/".$directory."/__trash/".$dirsource."/thumb");
        $urlsource=$racine."/".$directory."/".$dirsource."/thumb/".$namesource;
        $urldestination=$racine."/".$directory."/__trash/".$dirsource."/thumb/".$namesource;
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else $fs->rename($urlsource,$urldestination,true);
        }

        // Déplacer le thumbmini
        $fs->mkdir($racine."/".$directory."/__trash/".$dirsource."/thumbmini");
        $urlsource=$racine."/".$directory."/".$dirsource."/thumbmini/".$namesource;
        $urldestination=$racine."/".$directory."/__trash/".$dirsource."/thumbmini/".$namesource;
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else $fs->rename($urlsource,$urldestination,true);
        }

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

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

        $output=array();
        $directory=$request->request->get('directory');

        // Récupération du répertoire source et le nom du fichier
        $racine=$this->appKernel->getProjectDir()."/uploads/file";
        $directory=$request->request->get('directory');
        $dirsource  =$request->request->get('subdirectory');
        $namesource =$request->request->get('filename');

        $canupdate =$this->getPermission($em,$access,$directory);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');

        $fs = new Filesystem();

        // Déplacer le fichier
        $dirdestination=str_replace("__trash/","",$dirsource);
        $urlsource=$racine."/".$directory."/".$dirsource."/".$namesource;
        $urldestination=str_replace("__trash/","/",$urlsource);
        $fs->mkdir($racine."/".$directory."/".$dirdestination);
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else $fs->rename($urlsource,$urldestination,true);
        }

        // Déplacer le thumb
        $urlsource=$racine."/".$directory."/".$dirsource."/thumb/".$namesource;
        $urldestination=str_replace("__trash/","/",$urlsource);
        $fs->mkdir($racine."/".$directory."/".$dirdestination."/thumb");
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else $fs->rename($urlsource,$urldestination,true);
        }

        // Déplacer le thumbmini
        $urlsource=$racine."/".$directory."/".$dirsource."/thumbmini/".$namesource;
        $urldestination=str_replace("__trash/","/",$urlsource);
        $fs->mkdir($racine."/".$directory."/".$dirdestination."/thumbmini");
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else $fs->rename($urlsource,$urldestination,true);
        }

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

    public function purgetrash($directory, $access="config", Request $request, ManagerRegistry $em)
    {
        $output=array();

        $canupdate =$this->getPermission($em,$access,$directory);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');

        $fs = new Filesystem();
        $url=$this->appKernel->getProjectDir()."/uploads/file/".$directory."/__trash";
        if($fs->exists($url)) {
            $fs->remove($url);
        }

        return $this->redirectToRoute('app_core_'.$access.'_file_list',['directory'=>$directory]);             
    }

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

        $output=array();
        $directory=$request->request->get('directory');
        $subdirectory=$request->request->get('subdirectory');
        $filename=$request->request->get('filename');
        if($subdirectory) $directory.="/".$subdirectory;

        $canupdate =$this->getPermission($em,$access,$directory);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');

        $fs = new Filesystem();
        $url=$this->appKernel->getProjectDir()."/uploads/file/".$directory."/".$filename;
        if($fs->exists($url)) {
            $fs->remove($url);
        }

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

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

        $output=array();
        $directory=$request->request->get('directory');
        

        // Récupération du répertoire source et le nom du fichier
        $racine=$this->appKernel->getProjectDir()."/uploads/file";
        $directory = $request->request->get('directory');
        $dirsource = $request->request->get('dirsource');
        $namesource = $request->request->get('namesource');
        $dirdestination = $request->request->get('dirdestination');
        $namedestination = $request->request->get('namedestination');


        $canupdate =$this->getPermission($em,$access,$directory);
        if(!$canupdate) throw $this->createNotFoundException('Permission denied');
        
        $fs = new Filesystem();

        // Déplacer le fichier
        $urlsource=str_replace("//","/",$racine."/".$dirsource."/".$namesource);
        $urldestination=str_replace("//","/",$racine."/".$dirdestination."/".$namedestination);

        // Controle de cohérance du déplacement
        $fgerror=false;
        if(empty($racine)) $fgerror=true;
        if(empty($dirsource)) $fgerror=true;
        if(empty($directory)) $fgerror=true;
        if($urlsource==$urldestination) $fgerror=true;
        if(stripos($urldestination,$urlsource)!==false) $fgerror=true;
        if($fgerror) return new JsonResponse(array('message' => 'Interdit'), 400);


        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else 
                $fs->rename($urlsource,$urldestination, true);
        }

        // Déplacer le thumb
        $fs->mkdir($racine."/".$dirdestination."/thumb");
        $urlsource=$racine."/".$dirsource."/thumb/".$namesource;
        $urldestination=$racine."/".$dirdestination."/thumb/".$namedestination;
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else 
                $fs->rename($urlsource,$urldestination, true);
        }

        // Déplacer le thumbmini
        $fs->mkdir($racine."/".$dirdestination."/thumbmini");
        $urlsource=$racine."/".$dirsource."/thumbmini/".$namesource;
        $urldestination=$racine."/".$dirdestination."/thumbmini/".$namedestination;
        if($fs->exists($urlsource)) {
            if(is_dir($urlsource)) {
                $fs->mirror($urlsource,$urldestination);
                $fs->remove($urlsource);
            }
            else 
                $fs->rename($urlsource,$urldestination, true);
        }

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


    public function view($directory, $filename, $access="config", Request $request, ManagerRegistry $em)
    {
        $this->getPermission($em,$access,$directory);
        $subdirectory=$request->query->get('subdirectory');

        $navigation = $request->query->get('navigation');
        $tbprev=[];
        $tbnext=[];

        $url=$this->appKernel->getProjectDir()."/uploads/file/".$directory;
        if($subdirectory) $url.="/".$subdirectory;
        
        $url.="/".$filename;
        $file = new file($url);
        

        
        $minetype=$file->getMimeType();
        $minefamily=explode("/",$minetype)[0];

        if($minefamily=="text" || $minefamily=="image" || $minetype == "application/pdf") {
            $image="";
            if($minefamily=="image") {
                $image = "data:image/" . $file->getExtension() . ";base64," . base64_encode(file_get_contents($url));

                if($navigation) {
                    $dir=$this->appKernel->getProjectDir()."/uploads/file/".$directory;
                    $files=[];
                    $fs = new Filesystem();
            
                    if($fs->exists($dir)) {
                        $finder = new Finder();
                        $finder->sortByName()->in($dir)->exclude('thumb')->exclude("thumbmini");
                        
                        $i=-1;


                        foreach ($finder as $key => $file) {
                            $i++;

                            if($file->getRelativePathname()==$filename) {
                                $keyprev=$i-1;
                                $keynext=$i+1;
                            }

                            $tmp=[];
                            $tmp["name"]=$file->getRelativePathname();
                            $tmp["extension"]=$file->getExtension();
                            $fileinfo = new file($file->getPathname());
                            $tmp["minetype"]=$fileinfo->getMimeType();
                            $tmp["minefamily"]=explode("/",$tmp["minetype"])[0];
            
                            $tmp["thumb"]="";
                            if($fs->exists($dir."/thumb/".$tmp["name"])) {
                                $data = file_get_contents($dir."/thumb/".$tmp["name"]);
                                $tmp["thumb"]="data:image/" . $tmp["extension"] . ";base64," . base64_encode($data);
                            }
                            
                            array_push($files,$tmp);
                        }
                        
                        if(array_key_exists($keyprev,$files))
                            $tbprev=$files[$keyprev];
                        if(array_key_exists($keynext,$files))
                            $tbnext=$files[$keynext];
                    }
                }                
            }

            return $this->render('File\view.html.twig',[
                'useheader'     => false,
                'usemenu'       => false,
                'usesidebar'    => false,
                'access'        => $access,
                'directory'     => $directory,
                'subdirectory'  => $subdirectory,
                'minefamily'    => $minefamily,
                'minetype'      => $minetype,
                'filename'      => $filename,
                'image'         => $image,
                'prev'          => $tbprev,
                'next'          => $tbnext
            ]);
        }
        else {
            // normalement le widget ne fait jamais passer par là
            $response = new BinaryFileResponse($file);
            $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
            
            return $response;
        }
    }

    public function show($directory, $filename, $access="config", Request $request, ManagerRegistry $em)
    {
        $this->getPermission($em,$access,$directory);
        $subdirectory=$request->query->get('subdirectory');

        $file=$this->appKernel->getProjectDir()."/uploads/file/".$directory;
        if($subdirectory) $file.="/".$subdirectory;
        $file.="/".$filename;

        $response = new BinaryFileResponse($file);
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
        
        return $response;
    }

    public function download($directory, $filename, $access="config", Request $request, ManagerRegistry $em)
    {
        $this->getPermission($em,$access,$directory);
        $subdirectory=$request->query->get('subdirectory');

        $file=$this->appKernel->getProjectDir()."/uploads/file/".$directory;
        if($subdirectory) $file.="/".$subdirectory;
        $file.="/".$filename;

        $response = new BinaryFileResponse($file);
        $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT);
        
        return $response;
    }    

    public function getPermission($em, $access, $directory) {
        if($access=="user") {
            $type=explode("-",$directory)[0];
            $id=explode("-",$directory)[1];

            switch($type) {
                case "widget":
                    // Récupération du widget
                    $widget=$em->getRepository("App\Entity\Pagewidget")->find($id);
                    if (!$widget) throw $this->createNotFoundException('Unable to find entity.');

                    // On s'assure que l'utilisateur à la permission de voir
                    $page=$widget->getPage();
                    $em->getRepository("App\Entity\Page")->getPermission($this->getUser(),$page,$cansee,$canupdate,$canadd);
                    if(!$cansee) throw $this->createNotFoundException('Permission denied');                
                    return $canadd;
                break;

                case "projecttask":
                    // Récupération de la tache
                    $projecttask=$em->getRepository("App\Entity\Projecttask")->find($id);
                    if (!$projecttask) throw $this->createNotFoundException('Unable to find entity.');

                    // On s'assure que l'utilisateur à la permission de voir
                    $project=$projecttask->getProject();
                    $user=$this->getUser();
                    $em->getRepository("App\Entity\Project")->getPermission($user,$project,$cansee,$canupdate,$canadd);
                    if(!$cansee) throw $this->createNotFoundException('Permission denied');
                    return $canupdate;
                break;

                case "calendarevent":
                    // Récupération de l'event'
                    $calendarevent=$em->getRepository("App\Entity\Calendarevent")->find($id);
                    if (!$calendarevent) throw $this->createNotFoundException('Unable to find entity.');

                    // On s'assure que l'utilisateur à la permission de voir
                    $calendar=$calendarevent->getCalendar();
                    $user=$this->getUser();
                    $em->getRepository("App\Entity\Calendar")->getPermission($user,$calendar,$cansee,$canupdate,$canadd);
                    if(!$cansee) throw $this->createNotFoundException('Permission denied');
                    return $canadd;
                break;                
            }
        }
        else return true;
    }
}
