<?php

namespace Cadoles\PortalBundle\Service;

use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;

class onlyService
{  
    protected $container;
    protected $em;
    protected $only_activate = false;
    protected $only_url;
    protected $only_host;
    protected $only_user;
    protected $only_password;
    protected $debug = false;
    protected $headers = [];

    public function __construct($container, EntityManager $em)
    {
        $this->container = $container;
        $this->em = $em;
        
        $this->only_activate = $this->container->getParameter('activate_widonlyoffice');
        if($this->only_activate) {
            $this->only_activate=$this->container->getParameter('widonlyoffice_sync');
            if($this->only_activate) {
                $this->only_url         = $this->container->getParameter('widonlyoffice_url')."/api/2.0/";
                $this->only_user        = $this->container->getParameter('widonlyoffice_user');
                $this->only_password    = $this->container->getParameter('widonlyoffice_password');
                $this->only_host        = str_replace("https://","",str_replace("http://","",$this->container->getParameter("widonlyoffice_url")));
            }
        }
    }

    public function getDocument($idgroup,&$firstfolder,&$parents,&$tasks) {
        $files=[];
        $parents=[];
        $tasks=[];

        if(!is_null($idgroup)) {
            $group=$this->em->getRepository("CadolesCoreBundle:Group")->find($idgroup);
            if($group&&$group->getIdonlyoffice()) {
                if($this->only_activate) {
                    if($this->authOnly()) {
                        $response   = \Unirest\Request::get($this->only_url.'/project/'.$group->getIdonlyoffice(),$this->headers);
                        if(!$this->koresponse($response)) {
                            $home=$response->body->response->projectFolder;
                            if(!$firstfolder) $firstfolder=$response->body->response->projectFolder;
                        
                            $files[$firstfolder] = $this->scanfolder($firstfolder,"",$this->headers);
                            
                            // Construction du tableau des parents
                            $currentchild=$firstfolder;
                            
                            while($currentchild!=$home) {
                                $response   = \Unirest\Request::get($this->only_url.'/files/'.$currentchild,$this->headers);
                                if($this->koresponse($response)) return 0;

                                // Récupérer les informations du folder
                                $tmp=["id"=>$response->body->response->current->id,"name"=>$response->body->response->current->title];
                                array_push($parents,$tmp);

                                // Aller sur le folder parent
                                $currentchild=$response->body->response->current->parentId;
                            }

                            $response   = \Unirest\Request::get($this->only_url.'/project/'.$group->getIdonlyoffice().'/task/open',$this->headers);
                            if(!$this->koresponse($response)) $tasks=$response->body->response;  

                        }
                    }
                }
            }
        }

        return $files;
    }

    private function getFiles($idfolder) {

        return $files;
    }
    private function authOnly() {
        // Only Office est-il dans le domaine 
        if(stripos($this->only_url,"/")===0)
            $this->only_url="https://".$this->container->getParameter("weburl").$this->only_url;
        $indomaine = (stripos($this->only_url,$this->container->getParameter("weburl"))!==false);
    
        // Si hors domaine on utilise le proxy si proxy il y a 
        if(!$indomaine) {
            $PROXYactivate = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYactivate")->getValue();
            if($PROXYactivate) {
                $PROXYserver    = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYserver")->getValue();
                $PROXYport      = $this->em->getRepository("CadolesCoreBundle:Config")->find("PROXYport")->getValue();                    
                \Unirest\Request::proxy($PROXYserver, $PROXYport, CURLPROXY_HTTP, true);
            }
        }
    
        \Unirest\Request::verifyPeer(false);
        \Unirest\Request::verifyHost(false);
        \Unirest\Request::timeout(5);
        $this->headers  = ['Host' => $this->only_host, 'Accept' => 'application/json','Content-Type'=>'application/json','Retry-After'=>'5'];
        $query          = array('userName' => $this->only_user, 'password' => $this->only_password);
        $body           = \Unirest\Request\Body::json($query);
    
        $response   = \Unirest\Request::post($this->only_url.'/authentication',$this->headers,$body);
        if($this->koresponse($response)) return false;
        $token=$response->body->response->token;
        $this->headers["Authorization"]=$token;    
        return true;
    }
    
    private function koresponse($response) {
        if($response->code>=Response::HTTP_BAD_REQUEST) {
            $this->mydebug("ERREUR ".$response->code);
            if(property_exists($response,"body") && property_exists($response->body,"error")) $this->mydebug("ERREUR ".$response->body->error->message);;
            return true;
        }
    
        return false;
    } 

    private function mydebug($texte) {
        if($this->debug) error_log($texte);
    }

    private function scanfolder($folderid,$folderonly,$headers) {
        $files=["info"=>$folderonly,"files"=>[],"folders"=>[]];
        $response   = \Unirest\Request::get($this->only_url.'/files/'.$folderid,$headers);
        if($this->koresponse($response)) return 0;
        foreach($response->body->response->files as $fileonly) {
            array_push($files["files"],$fileonly);
        }
        foreach($response->body->response->folders as $folderonly) {
            $files["folders"][$folderonly->id] = $this->scanfolder($folderonly->id,$folderonly,$headers);
        }

        return $files;
    }

}
