<?php

namespace Helpers\Cache;

use Helpers\Log\LogSysteme;
use Helpers\Session\ParseBase1;
use Psr\SimpleCache\CacheInterface;

class Cache implements CacheInterface
{
    use APCu;

    public function __construct()
    {
    }
    
    public function get($key, $default = null)
    {
        if (\Helpers\Cache\Cache::variableTest() == true) {
            return $default;
        }
        $data = \apcu_fetch($key);
        return ($data !== false) ? $data : $default;
    }

    public function set($key, $value, $ttl = 0)
    {
        if ($ttl instanceof \DateInterval) {
            throw new \Exception('Not implemented');
        }
        $res = $this->surchargeSetUcache($key, $value, $ttl);
        if ($res === false) {
            LogSysteme::prefixErrorLog('apcu_store failed');
        }
        return $res;
    }

    public function delete($key)
    {
        $res = $this->surchargeDeleteUcache($key);
        if ($res === false) {
            LogSysteme::prefixErrorLog('apcu_delete failed');
        }
        return $res;
    }

    public function clear()
    {
        $res = $this->surchargeClearUcache();
        if ($res === false) {
            LogSysteme::prefixErrorLog('apcu_clear_cache failed');
        }
        return $res;
    }

    /**
     * @param iterable<mixed> $keys
     * @return iterable<mixed>
     */
    public function getMultiple($keys, $default = null)
    {
        throw new \Exception('Not implemented');
    }

    /**
     * @param iterable<mixed> $values
     */
    public function setMultiple($values, $ttl = null)
    {
        throw new \Exception('Not implemented');
    }
    
    /**
     * @param iterable<mixed> $keys
     */
    public function deleteMultiple($keys)
    {
        throw new \Exception('Not implemented');
    }

    public function has($key)
    {
        if (!is_string($key)) {
            throw new \Exception('!!!');
        }
        return \apcu_exists($key);
    }


    /**
     * variableTest
     *
     * @return bool
     */
    public static function variableTest() : bool
    {
        // TODO changer quand PHP à jour
        if (!\extension_loaded('APCu')) {
            return true;
        }
        
        return false;
    }
}
