<?php
namespace Fifa\ConnectServiceBus\Sdk\Utils;

use Fifa\ConnectServiceBus\Sdk\Authentication\CacheStorageInterface;

/**
 * Class Cache
 * @package Fifa\ConnectServiceBus\Sdk\Utils
 */
class SerializableCache
{
    /**
     * @var int
     */
    private $expirationTimeSpanInSeconds;

    /**
     * @var CacheStorageInterface
     */
    private $cacheStorage;

    /**
     * Cache constructor.
     * @param CacheStorageInterface $cacheStorage
     */
    public function __construct(CacheStorageInterface $cacheStorage)
    {
        $this->cacheStorage = $cacheStorage;
    }

    /**
     * Returns string representation of the object
     *
     * @return string
     */
    public function __toString()
    {
        return 'ExpirationTimeSpan: ' . $this->getExpirationTimeSpanInSeconds() . ' (s)';
    }

    /**
     * Sets validity limit
     *
     * @param int $expirationTimeSpanInSeconds
     * @return SerializableCache
     */
    public function setExpirationTimeSpanInSeconds(int $expirationTimeSpanInSeconds): SerializableCache
    {
        $this->expirationTimeSpanInSeconds = $expirationTimeSpanInSeconds;
        return $this;
    }

    /**
     * Gets validity limit
     *
     * @return int
     */
    public function getExpirationTimeSpanInSeconds(): int
    {
        return $this->expirationTimeSpanInSeconds;
    }

    /**
     * Gets data from cache.
     *
     * @param string $filenameKey
     * @return mixed|null
     */
    public function get(string $filenameKey)
    {
        $rawData = $this->cacheStorage->get($filenameKey);
        return unserialize($rawData);
    }

    /**
     * Store given object into cache
     *
     * @param string $filenameKey
     * @param mixed $object
     */
    public function put(string $filenameKey, $object)
    {
        $serializedData = serialize($object);
        $this->cacheStorage->put($serializedData, $filenameKey);
    }
}