<?php
class cdn
{
    protected $container;
    private $cdn;
    private $url;

    public function __construct($container) {
         $this->container = $container;
         $settings = $container->get('settings')['storage'];
         $this->url = $settings['url'];
         if($settings['type'] === 'ftp'){
            $this->cdn = new ftp($settings);
         }elseif($settings['type'] === 'blob'){
            $this->cdn = new blob($settings);
         }
    }

    public function initialize($config){
        //생성 후 값을 변경해야할때 사용
        $this->cdn->initialize($config);
    }

    public function uploadFile($file, $path)
    {
        return $this->cdn->uploadFile($file, $path);
    }

    public function copyFile($sourcepath, $destpath)
    {
        return $this->cdn->copyFile($sourcepath, $destpath);
    }    
    

    public function uploadText($text, $path, $options = [])
    {
        return $this->cdn->uploadText($text, $path, $options);
    }

    function formatSize($bytes, $decimals = 2) {
        $size = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        $factor = floor((strlen($bytes) - 1) / 3);
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
    }

    function purge($url){
        $this->cdn->purge($this->url.$url);
    }
        
    function array_sort($array, $on, $order=SORT_ASC)
    {
        $new_array = array();
        $sortable_array = array();

        if (count($array) > 0) {
            foreach ($array as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $on) {
                            $sortable_array[$k] = $v2;
                        }
                    }
                } else {
                    $sortable_array[$k] = $v;
                }
            }

            switch ($order) {
                case SORT_ASC:
                    asort($sortable_array);
                break;
                case SORT_DESC:
                    arsort($sortable_array);
                break;
            }

            foreach ($sortable_array as $k => $v) {
                $new_array[$k] = $array[$k];
            }
        }

        return $new_array;
    }
}
