<?php
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Blob\Models\CreateBlobOptions;
use MicrosoftAzure\Storage\Blob\Models\CreateBlockBlobOptions;
use MicrosoftAzure\Storage\Common\ServiceException;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Cdn\V20180606\CdnClient;
use TencentCloud\Cdn\V20180606\Models\PurgeUrlsCacheRequest;

class blob
{    
    private $container;
    private $accountname;
    private $accesskey;

    private $client;

    public function __construct($config){
        $this->container = $config['container'];
        $this->accountname = $config['id'];
        $this->accesskey = $config['pw'];
    }

    public function initialize($config){
        if(isset($config['container']))  $this->container = $config['container'];
        if(isset($config['id']))  $this->accountname = $config['id'];
        if(isset($config['pw']))  $this->accesskey = $config['pw'];        
    }
        
    public function is_connect(){
        return !empty($this->client);
    }
    
    private function _connect()
    {
        if($this->is_connect()){
            return true;
        }

        try {
            $connectionString = 'DefaultEndpointsProtocol=https;AccountName='.$this->accountname.';AccountKey='.$this->accesskey.';EndpointSuffix=core.windows.net'; //프로토콜이http이면 업로드를못한다.
            $this->client = BlobRestProxy::createBlobService($connectionString);

            return !empty($this->client);
        } catch (Exception $e) {
            return null;
        }
    }

    public function purge($url)
    {
        //cdn마다 purge방식이 달라 현재쓰는 퍼지를 구현해야함
        /*
        try {
            $cred = new Credential("IKIDFJ6csrZ1CCwPbXCagW4LM6ZlgKo2zjCO", "wb08zZsuf9MN9espVt0qPlqeCTTCNIwI");
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("cdn.tencentcloudapi.com");
              
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new CdnClient($cred, "", $clientProfile);
        
            $req = new PurgeUrlsCacheRequest();
            
            $params = array(
                "Urls" => array($url)
            );
            $req->fromJsonString(json_encode($params));
        
            $resp = $client->PurgeUrlsCache($req);
        
            $result = json_decode($resp->toJsonString(), true);
            return isset($result['TaskId']);
        }
        catch(TencentCloudSDKException $e) {
            return false;
        } 
        */
        return true;   
    }

    public function uploadFile($localfile, $remotepath)
    {
        ini_set('display_errors', '0');
        
        $result = false;

        if(empty($localfile) || empty($remotepath)) return $result;

        $this->_connect();
        $content = fopen($localfile, "r");

        try {
            //Upload blob
            $this->client->createBlockBlob($this->container, substr($remotepath,1), $content);
            $result = true;
        } catch(ServiceException $e){
            $code = $e->getCode();
            $error_message = $e->getMessage();
        }

        return $result;
    }

    public function copyFile($sourcepath, $destpath)
    {
        $result = false;

        if(empty($sourcepath) || empty($destpath)) return $result;

        $this->_connect();

        try {
            //Upload blob
            $result = $this->client->copyBlob($this->container, $destpath, $this->container, $sourcepath);
            $result = true;
        } catch(ServiceException $e){
            $code = $e->getCode();
            $error_message = $e->getMessage();
        }

        return $result;
    }

    public function uploadText($text, $remotepath, $options = [])
    {
        $result = false;

        $content = empty($text) ? "" : $text;
        if(empty($remotepath)) return $result;

        $this->_connect();

        try {
            $createBlockBlobOptions = new CreateBlockBlobOptions();
            if(!empty($options)) {
                if(!empty($options['contentType'])) {
                    $createBlockBlobOptions->setContentType($options['contentType']);
                }
            }
            //Upload blob
            $this->client->createBlockBlob($this->container, substr($remotepath,1), $content, $createBlockBlobOptions);
            $result = true;
        } catch(ServiceException $e){
            $code = $e->getCode();
            $error_message = $e->getMessage();
        }

        return $result;
    }
}