<?php

namespace Cadoles\PortalBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Session\Session;
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 Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;

class FrameController extends Controller
{

    public function onlyAction($directory,Request $request,$access="config") {

        $canupdate= $this->getPermission($access,$directory,$widget,$grp);
        $subdirectory=$request->get("subdirectory");
        $clear=$request->get("clear");
        $view=$request->get("view");
        $sort=$request->get("sort");
        $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érence trie 
        if(!array_key_exists("widgetsortdirectory",$preference)) {
            $toupdate=true;
            $preference["widgetsortdirectory"]=[];
        }
        if((!array_key_exists($directory,$preference["widgetsortdirectory"]))) {
            $toupdate=true;
            $preference["widgetsortdirectory"][$directory]="title";
        }
        if($sort&&$preference["widgetsortdirectory"][$directory]!=$sort) {
            $toupdate=true;
            $preference["widgetsortdirectory"][$directory]=$sort;            
        }

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

        // Initialiser le service only
        $onlyservice = $this->container->get('cadoles.portal.service.only');
        $firstfolder=($subdirectory?$subdirectory:null);
        $files=$onlyservice->getDocument($grp->getId(), $firstfolder, $parents, $tasks);

        // Trie Fichier
        $tmpfiles=$files[$firstfolder]["files"];
        foreach($tmpfiles as $key => $value) {
            $tmpfiles[$key]->author=$value->updatedBy->displayName;
            $tmpfiles[$key]->updatedformat= date('d/m/Y h:i', strtotime($value->updated));
        }
        $sort = array_column($tmpfiles, $preference["widgetsortdirectory"][$directory]);
        array_multisort($sort, SORT_ASC, $tmpfiles);
        $files[$firstfolder]["files"] = $tmpfiles;

        // Trie Dossier
        $tmpdirs=$files[$firstfolder]["folders"];
        foreach($tmpdirs as $key => $value) {
            $tmpdirs[$key]["title"]=$value["info"]->title;
            $tmpdirs[$key]["updated"]= $value["info"]->updated;
            $tmpdirs[$key]["updatedformat"]= date('d/m/Y h:i', strtotime($value["info"]->updated));
            $tmpdirs[$key]["author"]=$value["info"]->updatedBy->displayName;
        }
        $sort = array_column($tmpdirs, $preference["widgetsortdirectory"][$directory]);
        array_multisort($sort, SORT_ASC, $tmpdirs);
        $files[$firstfolder]["folders"] = $tmpdirs;

        //$sort = array_column($tmpfiles, $preference["widgetsortdirectory"][$directory]);
        //array_multisort($sort, SORT_ASC, $tmpfiles);
        //$files[$firstfolder]["files"] = $tmpfiles;


        // Récupération du numéro de groupe oo
        if($grp) $idonly= $grp->getIdOnlyoffice();
        else $idonly=0;

        // Récupération des paramétres du widget
        $apponly=0;
        foreach($widget->getParameter()["fields"] as $parameter) {
            switch($parameter["id"]) {     
                case "apponly":
                    $apponly=$parameter["value"];
                    break;                             
            }
        } 

        return $this->render('CadolesPortalBundle:Frame:only.html.twig',[
            'useheader'     => false,
            'usemenu'       => false,
            'usesidebar'    => false,
            'access'        => $access,
            'urlonly'       => $this->getParameter("widonlyoffice_url")."/products/projects/tmdocs.aspx?prjID=".$idonly."#".$firstfolder,
            'directory'     => $directory,
            'parents'       => $parents,
            'subdirectory'  => $subdirectory,
            'files'         => $files,
            'canupdate'     => $canupdate,
            'view'          => $preference["widgetviewdirectory"][$directory],
            'sort'          => $preference["widgetsortdirectory"][$directory],
            'tasks'         => $tasks,
            'apponly'       => $apponly
        ]);  
    }


    public function getPermission($access, $id, &$widget, &$group) {
        $em = $this->getDoctrine()->getManager();

        // Récupération du widget & de la page
        $widget=$em->getRepository("CadolesPortalBundle:Pagewidget")->find($id);
        if (!$widget) throw $this->createNotFoundException('Unable to find entity.');
        $page=$widget->getPage();

        $groups=$page->getGroups();
        $group=$groups[0];

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

        return $canupdate;
    }
}
