<?php
/**
 * @package DJ-Catalog2-Yootheme
 * @copyright Copyright (C) DJ-Extensions.com, All rights reserved.
 * @license http://www.gnu.org/licenses GNU/GPL
 * @author url: http://dj-extensions.com
 * @author email contact@dj-extensions.com
 */

namespace DJExtensions\DJCatalog2\YOOtheme\Layouts;
defined('_JEXEC') or die;
use YOOtheme\File;
use YOOtheme\Path;

class Cache
{
    /**
     * @var string
     */
    protected $prefix;

    /**
     * @var string
     */
    protected $cache;

    /**
     * Constructor.
     *
     * @param string $prefix
     */
    public function __construct($prefix)
    {
        $this->prefix = $prefix;
        $this->cache = Path::resolve('~theme/cache/djcatalog2');

        File::makeDir($this->cache, 0777, true);
    }

    /**
     * Return the cache path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->cache;
    }

    /**
     * Returns the cached asset path
     *
     * @param string $name
     *
     * @return string|null
     */
    public function get($name)
    {
        $file = $this->resolve($name);

        if (File::exists($file)) {
            return File::getContents($file);
        }
    }

    /**
     * Saves the asset in the resolved cache ubication
     *
     * @param string $name
     * @param mixed $data
     *
     * @return int|null
     */
    public function set($name, $data)
    {
        return File::putContents($this->resolve($name), $data);
    }

    /**
     * Checks whether asset is cached
     *
     * @param string $name
     *
     * @return bool
     */
    public function exists($name)
    {
        return File::exists($this->resolve($name));
    }

    /**
     * Gets the inode change time of asset
     *
     * @param string $name
     *
     * @return bool
     */
    public function getCTime($name)
    {
        return File::getCTime($this->resolve($name));
    }

    /**
     * Resolves path to cache asset
     *
     * @param string $name
     *
     * @return string
     */
    public function resolve($name)
    {
        return Path::resolve($this->cache, "$this->prefix-$name");
    }
}
