<?php

namespace Velis\Cache;

use Phalcon\Cache\Adapter\AdapterInterface;
use Phalcon\Cache\Adapter\Stream;
use Phalcon\Proxy\Psr16\Cache;
use Phalcon\Storage\Exception;
use Phalcon\Storage\SerializerFactory;
use Velis\App;
use Velis\App\PhalconVersion;
use Velis\Cache\Adapter\Phalcon4RedisAdapter;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class CacheFactory implements CacheFactoryInterface
{
    /**
     * {@inheritDoc}
     * @throws Exception
     */
    public function createFileCache(array $options): CacheInterface
    {
        $serializerFactory = new SerializerFactory();
        $directory = $options['directory'] ?? 'cache';
        $options['storageDir'] = DATA_PATH . $directory . '/';
        $options['lifetime'] = $options['ttl'] ?? App::CACHE_24H;
        $options['prefix'] = '';

        $adapter = new Stream($serializerFactory, $options);
        $phalconCache = $this->createPhalconCache($adapter);
        $debug = App::devMode();

        return new FileCache($phalconCache, $debug, $directory);
    }

    /**
     * @param AdapterInterface $adapter
     * @return \Phalcon\Cache|Cache
     */
    private function createPhalconCache(AdapterInterface $adapter)
    {
        if (App::getPhalconMajorVersion() >= PhalconVersion::PHALCON5) {
            return new Cache($adapter);
        } else {
            return new \Phalcon\Cache($adapter);
        }
    }

    /**
     * {@inheritDoc}
     * @throws \Phalcon\Support\Exception
     */
    public function createRedisCache(array $options): CacheInterface
    {
        $serializerFactory = new SerializerFactory();
        $options['lifetime'] = $options['ttl'] ?? App::CACHE_24H;

        $adapter = new Phalcon4RedisAdapter($serializerFactory, $options);
        $phalconCache = $this->createPhalconCache($adapter);
        $debug = App::devMode();

        return new RedisCache($phalconCache, $debug);
    }
}
