<?php

/**
 * @see Zend_View_Helper_Abstract
 */
goweb::loadClass('Zend_View_Helper_Abstract');

/**
 * @see JSMin
 */
require_once LIBRARY_PATH . '/External/jsmin.php';

/**
 * Goweb Sitemanager 5 Framework
 *
 * Retorna os Javascripts para serem carregados.
 *
 * @version    5.0.20
 * @category   Goweb
 * @package    Goweb_View_Helper_GetJavascript
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2010 (c) Goweb (http://www.goweb.pt)
 *
 *
 */

class Goweb_View_Helper_GetJavascriptsMinified extends Zend_View_Helper_Abstract{

    /**
     * Retorna os Javascripts para serem carregados.
     *
     * @return array
     */
    public function GetJavascriptsMinified(){
        $dir = WWW_PATH.'/media/js/';
        if (!file_exists($dir)) {
            mkdir($dir, 0777, true);
        }
        $jsFiles = Goweb::getJavascripts();
        $lastmodified = 0;
        foreach ($jsFiles as $jsFile){
            if (is_file(WWW_PATH . $jsFile)){
                $lastmodified = max($lastmodified, filemtime(WWW_PATH . $jsFile));
            }
        }

        $md5File = $lastmodified . '-' . md5(serialize($jsFiles)) . '.js';

        if (!is_file($dir . $md5File)){
            $list = glob($dir . '*-' . md5(serialize($jsFiles)) . '.js');
            if (count($list) > 0){
                /**
                 * Remover ficheiros anteriores
                 */
                foreach ($list as $file){
                    if (is_writable($file)){
                        @unlink($file);
                    }
                }
            }
            $contents = '';
            foreach ($jsFiles as $jsFile){
                if (is_file(WWW_PATH . $jsFile)){
                    $contents .= "\n\n" . JSMin::minify(file_get_contents(WWW_PATH . $jsFile));
                }
            }
            if ($fp = fopen($dir . $md5File, 'wb')) {
                fwrite($fp, $contents);
                fclose($fp);
            }
        }
        return '/media/js/' . $md5File;
    }
}
