<?php


namespace Union\Core\View\Helper;

use JBZoo\Utils\FS;
use Cake\Routing\Router;
use Cake\Core\Configure;
use Cake\View\Helper\UrlHelper as CakeUrlHelper;

/**
 * Class UrlHelper
 *
 * @package Union\Core\View\Helper
 * @property \Union\Core\View\AppView $_View
 */
class UrlHelper extends CakeUrlHelper
{

    /**
     * Generates URL for given CSS file.
     *
     * @param array|string $path
     * @param array $options
     * @return array|null|string
     */
    public function css($path, array $options = [])
    {
        return $this->assetUrl($path, $options);
    }

    /**
     * Generates URL for given JS file.
     *
     * @param array|string $path
     * @param array $options
     * @return array|null|string
     */
    public function script($path, array $options = [])
    {
        return $this->assetUrl($path, $options);
    }

    /**
     * Generates URL for given asset file.
     *
     * @param array|string $path
     * @param array $options
     * @return array|null|string
     */
    public function assetUrl($path, array $options = [])
    {
        if (is_array($path)) {
            return $this->build($path, !empty($options['fullBase']));
        }

        if (empty(FS::ext($path))) {
            $path .= '.' . $options['ext'];
        }

        $Path = $this->_View->getPath();
        $relative = ($Path->isVirtual($path)) ? $Path->get($path) : $Path->get('root:' . $path);

        if (strpos($path, '://') !== false) {
            return $path;
        }
        
        if ($relative !== null) {
            $path = $Path->url($this->_encodeUrl($this->assetTimestamp($relative)), false);

            if (!empty($options['fullBase'])) {
                 $path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
            }

            return $path;
        }

        return null;
    }

    /**
     * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in  Configure.
     *
     * @param string $path
     * @return null|string
     */
    public function assetTimestamp($path)
    {
        if ($this->_timeStampEnable() && strpos($path, '?') === false) {
            $Path = $this->_View->getPath();
            if ($Path->isVirtual($path)) {
                $path = $Path->get($path);
            }

            if (FS::isFile($path)) {
                //@codingStandardsIgnoreStart
                return $path . '?' . @filemtime($path);
                //@codingStandardsIgnoreEnd
            }
        }

        return $path;
    }

    /**
     * Check timestamp is enabled.
     *
     * @return bool
     */
    protected function _timeStampEnable()
    {
        $stamp = Configure::read('Asset.timestamp');
        return $stamp === 'force' || ($stamp === true && Configure::read('debug'));
    }
}
