<?php

namespace Plugin\ApgSimpleCalendar\Repository;

use Eccube\Repository\AbstractRepository;
use Plugin\ApgSimpleCalendar\Entity\Config;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * ConfigRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ConfigRepository extends AbstractRepository
{

    const CASH_KEY_GET = 'apg_sc_config_get';
    const CASH_KEY_FIND_ALL = 'apg_sc_config_find_all';
    const CASH_ALL = [
        self::CASH_KEY_GET,
        self::CASH_KEY_FIND_ALL,
    ];

    /**
     * ConfigRepository constructor.
     *
     * @param RegistryInterface $registry
     */
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Config::class);
    }

    /**
     * @param int $id
     *
     * @return null|Config
     */
    public function get($id = 1)
    {
        return $this->find($id);
    }

    public function getWithCache($id = 1)
    {

        $lifetime = $this->getCacheLifetime();
        $qb = $this->createQueryBuilder('b')
            ->where('b.id = :id')
            ->setParameter('id', $id);

        $recode = $qb->getQuery()
            ->useResultCache(true, $lifetime, self::CASH_KEY_GET)
            ->getOneOrNullResult();
        return empty($recode) ? new Config() : $recode;

    }

    public function findAllWithCache()
    {
        $lifetime = $this->getCacheLifetime();
        $qb = $this->createQueryBuilder('c');
        return $qb->getQuery()
            ->useResultCache(true, $lifetime, self::CASH_KEY_FIND_ALL)
            ->getArrayResult();
    }

    public function save($entity)
    {
        $result = parent::save($entity);
        $this->cacheClear();
        return $result;
    }


    public function cacheClear()
    {
        $em = $this->getEntityManager();
        $cacheImpl = $em->getConfiguration()->getResultCacheImpl();
        if (!empty($cacheImpl)) {
            foreach (self::CASH_ALL as $cacheKey) {
                $cacheImpl->delete($cacheKey);
            }
        }
    }
}
