<?php

namespace Plugins\DocumentPlugin;

use Core\View\View;
use Core\View\ElementView;
use Core\Core\Response;
use Core\Core\Request;
use Core\Control\Upload\Upload;
use Core\Utility\File\File;

use Plugins\DocumentPlugin\Widget\DocumentPluginDocumentForm\DocumentPluginDocumentForm;
use Plugins\DocumentPlugin\Entity\DocumentEntity;

class DocumentPlugin {
    
    public $Author = 'Webemyos';
    public $Version = '1.0.0.0';
    
    function __construct($core) {
        $this->Core = $core;
    }

    function renderAdmin($appName){
        $view = new View(__DIR__ . "/View/admin.tpl", $this->Core); 

        $documentForm = new DocumentPluginDocumentForm($this->Core, ["AppName" => $appName,
                                                                     "EntityName" => $appName."Document"]);
          
        $view->AddElement(new ElementView("upload", $documentForm->Render($appName)));
        $view->AddElement(new ElementView("pluginScript", $this->GetRegister()));
       
        $view->AddElement(new ElementView("documents", $this->GetDocuments($appName)));
        
        return $view->Render() ;
   }
    
   function renderMember($appName, $entityId){
    $view = new View(__DIR__ . "/View/member.tpl", $this->Core); 

    $documentForm = new DocumentPluginDocumentForm($this->Core, [ "AppName" => $appName,
                                                                  "EntityName" => $appName."Document",
                                                                  "EntityId"  => $entityId]);
      
    $view->AddElement(new ElementView("upload", $documentForm->Render($appName)));
    $view->AddElement(new ElementView("pluginScript", $this->GetRegister()));
   
    $view->AddElement(new ElementView("documentsUpload", $this->GetDocuments($appName, "", false)));
 
    $view->AddElement(new ElementView("documents", $this->GetDocuments($appName, $entityId)));
    
    return $view->Render() ;
    }
   

    function RenderDetailMember($appName, $entityId){
    $view = new View(__DIR__ . "/View/detailMember.tpl", $this->Core); 

    $documentForm = new DocumentPluginDocumentForm($this->Core, [ "AppName" => $appName,
                                                                  "EntityName" => $appName."Document",
                                                                  "EntityId"  => $entityId]);
    
    $view->AddElement(new ElementView("documents", $this->GetDocuments($appName, $entityId, false, 4)));
    
    return $view->Render() ;
    }

   function GetDocuments($appName, $entityId ="", $showTrash = true, $widthDoc = "2"){
        $view = new View(__DIR__ . "/View/documents.tpl", $this->Core);
         
        //Récupération des document non lié a des entité
        $document = new DocumentEntity($this->Core);

        if($entityId == ""){
            $documents = $document->Find("EntityName = '".$appName."Document' AND EntityId is null");
        } else{
            $documents = $document->Find("EntityName = '".$appName."Document' AND EntityId =" .$entityId );
        }
        $view->AddElement(new ElementView("showTrash", $showTrash));
      
        $view->AddElement(new ElementView("documents", $documents));
        $view->AddElement(new ElementView("widthDoc", $widthDoc));
        
        
        
        return $view->Render();
   }
   
    /*     * *
     * Comment Type
     */

    function GetType() {
        return "Document";
    }
    
    /***
     * 
     */
    function GetRegister(){
       return "Plugin.Register('DocumentPlugin', 'DocumentPlugin', function(){ DocumentPlugin.Init(); });" ;
    }
    
    /****
     * Sauvegarde un document
     */
    function SendDocument($params){
        $entityName = $params->entityName;
        $entityId = $params->entityId;
        $appName = $params->appName;
        
        $files = base64_decode($params->files);
        
        preg_match('/=Data\/Tmp\/[^&]+/', $files, $matches);

        if (!empty($matches)) {
            $tmpFile = substr($matches[0], 1); // On enlève le "=" au début
   
            //on transfert le ficheir
            mkdir("Data/Apps/DocumentPlugin");
            
            $finalName = str_replace("Data/Tmp", "Data/Apps/DocumentPlugin", $tmpFile);
            
            rename($tmpFile, $finalName);
            
            $document = new DocumentEntity($this->Core);
            $document->EntityName->Value = $entityName;
            $document->EntityId->Value = $entityId;
           
            $document->FileName->Value = basename($finalName);
            $document->Url->Value = $this->Core->GetPath("/".$finalName);
            $document->Save();
            
            return $this->GetDocuments($appName, $entityId);
      
        } 
    }
    
    /**
     * Supprime un document
     * @param type $params
     */
    function RemoveDocument($params){
        
        $document = new DocumentEntity($this->Core);
        $document->GetById($params->fileId);
        
        File::Delete($document->FileName->Value, "Data/Apps/DocumentPlugin/");
        $document->Delete();
    }
    
    /***
     * Get the document to download and the user document
     */
    function GetInfoByAppAndEntity($params){
       $entityName = Request::GetPost("EntityName");
       $entityId = Request::GetPost("EntityId");
       
        //Récupération des document non lié a des entité
        $document = new DocumentEntity($this->Core);

       $uploadDocument = $document->Find("EntityName = '".$entityName."Document' AND EntityId is null");
       
       $userDocument = $document->Find("EntityName = '".$entityName."Document' AND EntityId =" .$entityId);
       
       return Response::Success(["uploadDocument" => $document->ToAllArray($uploadDocument),
                                 "userDocument" => $document->ToAllArray($userDocument),
           ]);
    }
    
    function AddDocumentEntity($params){
        $entityName = $_POST["entityName"];
        $entityId = $_POST["entityId"];
        $fileName = basename($_FILES['file']['name']);
        
        $finalName = "Data/Apps/DocumentPlugin/". $fileName;
        $_FILES['file']['tmp_name'];
        
        
        move_uploaded_file($_FILES['file']['tmp_name'], $finalName);
            
        $document = new DocumentEntity($this->Core);
        $document->EntityName->Value = $entityName;
        $document->EntityId->Value = $entityId;

        $document->FileName->Value = basename($finalName);
        $document->Url->Value = $this->Core->GetPath("/".$finalName);
        $document->Save();
        
         return Response::Success([]);
    }
    
}