<?php

namespace Mailbox\Infrastructure\Repositories\Helpers;

use Mailbox\Domain\MailBox\MailBoxCollection;
use Mailbox\Domain\Message\Message;
use Mailbox\Infrastructure\Repositories\RepositoryCacheInterface;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\NullAdapter;
use Zend\Mail\Storage\Folder;

trait CacheHelperTrait
{
    /**
     * @param RepositoryCacheInterface $config
     */
    private function initCache(RepositoryCacheInterface $config): void
    {

        if ($config->getCacheDir() === null) {
            $this->cacheAdapter = new NullAdapter();
        } else {
            $this->cacheAdapter = new FilesystemAdapter(
                '',
                0,
                $this->createCacheDirName($config)
            );
        }
    }

    /**
     * @param RepositoryCacheInterface $config
     * @return string
     */
    protected function createCacheDirName(RepositoryCacheInterface $config)
    {
        return $config->getCacheDir() . "/" . $config->getLogin();
    }

    /**
     * @param string $key
     * @return |null
     */
    private function needInCache(string $key)
    {
        $cacheMessage = $this->cacheAdapter->getItem($key);

        if ($cacheMessage->isHit() === false) {
            return null;
        }

        return $cacheMessage->get();
    }

    /**
     * @return array|null
     */
    private function needBoxesInCache(): ?array
    {
        $mailBoxes = $this->cacheAdapter->getItem("mailBoxes");

        if ($mailBoxes->isHit() === false) {
            return null;
        }

        return $mailBoxes->get();
    }

    /**
     * @param array $mailBoxCollection
     */
    private function saveBoxesInCache(array $mailBoxCollection): void
    {
        $mailBoxes = $this->cacheAdapter->getItem("mailBoxes");
        $mailBoxes->set($mailBoxCollection);
        $mailBoxes->expiresAfter(300);//Время эизни ограниченно и это должно работать!!!
        $this->cacheAdapter->save($mailBoxes);
    }

    /**
     * @param string $message
     * @param string $key
     */
    private function saveInCache(string $message, string $key): void
    {
        $cacheMessage = $this->cacheAdapter->getItem($key);
        $cacheMessage->set($message);
        $this->cacheAdapter->save($cacheMessage);
    }
}
