<?php
/**
 * Created by IntelliJ IDEA.
 * User: damien
 * Date: 11/02/2017
 * Time: 16:48
 */

namespace Actigraph\ActipageBaseBundle\Services;

use CloudFileStorage;
use CloudFileStorage\AdapterFilesystem;
use ReflectionClass;

class FilesService
{
    /** @var $cloudFilesStorage AdapterFilesystem */
    private $cloudFilesStorage;
    private $params,$adapterClass,$adapterParameter;

    public function __construct($params)
    {
        if(!$params["cloudStorage"])
            return;
        $this->params = $params["cloudStorage"];
        if($this->params["adapter"] == "opencloud"){
            $this->adapterClass = "CloudFileStorage\\Adapter\\OpenCloud";
            $this->adapterParameter = $this->params["opencloud"];
        }else if($this->params["adapter"] == "s3"){
            $this->adapterClass = "CloudFileStorage\\Adapter\\S3Cloud";
            $this->adapterParameter = $this->params["s3"];
        }
    }
    private function ensureCloudFileStorageInstanceExist(){
        if(!$this->isCloudFileStorageInstanceExist()){
            $adapterClass = new ReflectionClass($this->adapterClass);
            // Pas de cache car quand nouvel élément dans galerie on ne sait pas quand invalider le cache
            $adapter = $adapterClass->newInstance($this->adapterParameter, []);
            $this->cloudFilesStorage= new CloudFileStorage\Filesystem($adapter);
        }
    }
    private function isCloudFileStorageInstanceExist(){
        return $this->cloudFilesStorage != null;
    }

    public function getTemporyUrlForPath($path){
        $dateExpiration = new \DateTime();
        $dateExpiration->setTime(23, 59, 59);

        //TODO gestion inteligente de la date d'expiration pour que ça soit l'heure suivante toujours, ainsi le cache navigateur fonctionnera
        $adapterClass = new ReflectionClass($this->adapterClass);
        $adapterStaticGenerateTemporyUrl = $adapterClass->getMethod("staticGenerateTemporyUrl");
        return $adapterStaticGenerateTemporyUrl->invokeArgs(null,array($this->adapterParameter,$path,$dateExpiration));

    }

    public function listPath($path){
        $this->ensureCloudFileStorageInstanceExist();
        $resultat = $this->cloudFilesStorage->listeObjets($path);
        return $resultat;
    }

    public function uploadFile($path, $localPath){
        $this->ensureCloudFileStorageInstanceExist();
        $this->cloudFilesStorage->uploadLocalFile($path, $localPath);
    }
    public function deleteFile($path){
        $this->ensureCloudFileStorageInstanceExist();
        return $this->cloudFilesStorage->deleteFile($path);
    }

    public function deleteFiles($paths){
        $this->ensureCloudFileStorageInstanceExist();
        return $this->cloudFilesStorage->deleteFiles($paths);
    }

    public function checkExistingFile($path){
        $this->ensureCloudFileStorageInstanceExist();
        return $this->cloudFilesStorage->exists($path);
    }

}
