<?php

class Media extends MediaCore
{
    public static function cccCss($css_files)
    {
        require_once(dirname(__FILE__).'../../../modules/designer/defines.inc.php');
        //inits
        $css_files_by_media = array();
        $compressed_css_files = array();
        $compressed_css_files_not_found = array();
        $compressed_css_files_infos = array();
        $protocol_link = Tools::getCurrentUrlProtocolPrefix();

        $theme_dir = getThemeDir();
        $theme_name = getThemeName();

        // group css files by media
        foreach ($css_files as $filename => $media)
        {
            if (!array_key_exists($media, $css_files_by_media))
                $css_files_by_media[$media] = array();

            $infos = array();
            $infos['uri'] = $filename;
            $url_data = parse_url($filename);
            $infos['path'] = _PS_ROOT_DIR_.Tools::str_replace_once(__PS_BASE_URI__, '/', $url_data['path']);
            $css_files_by_media[$media]['files'][] = $infos;
            if (!array_key_exists('date', $css_files_by_media[$media]))
                $css_files_by_media[$media]['date'] = 0;
            $css_files_by_media[$media]['date'] = max(
                file_exists($infos['path']) ? filemtime($infos['path']) : 0,
                $css_files_by_media[$media]['date']
            );

            if (!array_key_exists($media, $compressed_css_files_infos))
                $compressed_css_files_infos[$media] = array('key' => '');
            $compressed_css_files_infos[$media]['key'] .= $filename;
        }

        // get compressed css file infos
        foreach ($compressed_css_files_infos as $media => &$info)
        {
            $key = md5($info['key'].$protocol_link);
            $filename = $theme_dir.'cache/'.$key.'_'.$media.'.css';
            $info = array(
                'key' => $key,
                'date' => file_exists($filename) ? filemtime($filename) : 0
            );
        }

        // aggregate and compress css files content, write new caches files
        $import_url = array();
        foreach ($css_files_by_media as $media => $media_infos)
        {
            $cache_filename = $theme_dir.'cache/'.$compressed_css_files_infos[$media]['key'].'_'.$media.'.css';
            if ($media_infos['date'] > $compressed_css_files_infos[$media]['date'])
            {
                $compressed_css_files[$media] = '';
                foreach ($media_infos['files'] as $file_infos)
                {
                    if (file_exists($file_infos['path']))
                        $compressed_css_files[$media] .= Media::minifyCSS(file_get_contents($file_infos['path']), $file_infos['uri'], $import_url);
                    else
                        $compressed_css_files_not_found[] = $file_infos['path'];
                }
                if (!empty($compressed_css_files_not_found))
                    $content = '/* WARNING ! file(s) not found : "'.
                        implode(',', $compressed_css_files_not_found).
                        '" */'."\n".$compressed_css_files[$media];
                else
                    $content = $compressed_css_files[$media];

                $content = implode('', $import_url).$content;
                file_put_contents($cache_filename, $content);
                chmod($cache_filename, 0777);
            }
            $compressed_css_files[$media] = $cache_filename;
        }

        // rebuild the original css_files array
        $css_files = array();
        foreach ($compressed_css_files as $media => $filename)
        {
            
            $url = str_replace($theme_dir, _THEMES_DIR_.$theme_name.'/', $filename);
            $css_files[$protocol_link.Tools::getMediaServer($url).$url] = $media;
        }
        return $css_files;
    }


    /**
    * Combine Compress and Cache (ccc) JS calls
    *
    * @@param array js_files
    * @@return array processed js_files
    */
    public static function cccJS($js_files)
    {
        require_once(dirname(__FILE__).'../../../modules/designer/defines.inc.php');
        //inits
        $compressed_js_files_not_found = array();
        $js_files_infos = array();
        $js_files_date = 0;
        $compressed_js_filename = '';
        $js_external_files = array();
        $protocol_link = Tools::getCurrentUrlProtocolPrefix();

        // get js files infos
        foreach ($js_files as $filename)
        {
            $expr = explode(':', $filename);

            if ($expr[0] == 'http')
                $js_external_files[] = $filename;
            else
            {
                $infos = array();
                $infos['uri'] = $filename;
                $url_data = parse_url($filename);
                $infos['path'] = _PS_ROOT_DIR_.Tools::str_replace_once(__PS_BASE_URI__, '/', $url_data['path']);
                $js_files_infos[] = $infos;

                $js_files_date = max(
                    file_exists($infos['path']) ? filemtime($infos['path']) : 0,
                    $js_files_date
                );
                $compressed_js_filename .= $filename;
            }
        }

        // get compressed js file infos
        $compressed_js_filename = md5($compressed_js_filename);

        $compressed_js_path = getThemeDir().'cache/'.$compressed_js_filename.'.js';
        $compressed_js_file_date = file_exists($compressed_js_path) ? filemtime($compressed_js_path) : 0;

        // aggregate and compress js files content, write new caches files
        if ($js_files_date > $compressed_js_file_date)
        {
            $content = '';
            foreach ($js_files_infos as $file_infos)
            {
                if (file_exists($file_infos['path']))
                    $content .= file_get_contents($file_infos['path']).';';
                else
                    $compressed_js_files_not_found[] = $file_infos['path'];
            }
            $content = Media::packJS($content);

            if (!empty($compressed_js_files_not_found))
                $content = '/* WARNING ! file(s) not found : "'.
                    implode(',', $compressed_js_files_not_found).
                    '" */'."\n".$content;

            file_put_contents($compressed_js_path, $content);
            chmod($compressed_js_path, 0777);
        }

        // rebuild the original js_files array
        $url = str_replace(_PS_ROOT_DIR_.'/', __PS_BASE_URI__, $compressed_js_path);

        return array_merge(array($protocol_link.Tools::getMediaServer($url).$url), $js_external_files);
    }
}