<?php
/**
 * core.framework
 *
 * @category  Core
 * @package   Core_Asset
 * @copyright Copyright (c) 2013. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */

/**
 * @category  Core
 * @package   Core_Asset
 * @copyright Copyright (c) 2013. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */
class Core_Asset extends Core_Storage_File
{
    /**
     * Content buffer
     * @var string
     */
    protected $_content     = '';

    protected $_cachebust   = false;

    /**
     * Returns asset content as string
     *
     * @return  string
     */
    public function __toString()
    {
        if ($this->_content === '') {
            $pathComponents = explode('?', $this->getPath());
            $this->_content = file_get_contents($pathComponents[0]);
        }
        return $this->_content;
    }

    /**
     * Set Cache busting on/off
     *
     * @param   boolean     $value
     *
     * @return  \Core_Asset
     */
    public function setCacheBust($value)
    {
        $this->_cachebust = (bool) $value;
        return $this;
    }

    /**
     * Is cache bust flag set?
     *
     * @return  boolean
     */
    public function isCacheBust()
    {
        return $this->_cachebust;
    }

    /**
     * Get Url
     * - with or without cache busting string
     *
     * @return  string
     */
    public function getUrl()
    {
        $domain = $this->getStorage()->getDomain();

        if ($this->_url !== null) {
            $assetUrl = $domain . $this->_url;
        } else {
            $assetUrl = parent::getUrl();
        }

        // remove parameters if they exist
        list($url) = explode('?', $assetUrl);

        if ($this->isCacheBust()) {
            $pathComponents = explode('?', $this->getPath());
            $dataHash       = md5(file_get_contents($pathComponents[0]));
            $url .= '?v='. $dataHash;
        }
        return $url;
    }

    /**
     * Get Url
     * - with or without cache busting string
     *
     * @return  string
     */
    public function getUrlPath()
    {
        if ($this->_url !== null) {
            $assetUrl = $this->_url;
        } else {
            $assetUrl = parent::getUrl();
        }

        // remove parameters if they exist
        list($url) = explode('?', $assetUrl);

        if ($this->isCacheBust()) {
            $pathComponents = explode('?', $this->getPath());
            $dataHash       = md5(file_get_contents($pathComponents[0]));
            $url .= '?v='. $dataHash;
        }
        return $url;
    }


//    /**
//     * Dump asset contents
//     *
//     * @return  string
//     */
//    public function dump()
//    {
//        $path = $this->getPath();
//
//        if (!file_exists($path)) {
//            throw new InvalidArgumentException('Unable to dump asset, file does\'nt exist: '. $path);
//        }
//
//        return "TEMP STRING";
//        // return file_get_contents($path);
//    }

}