<?php

namespace Dipper\Foundation\Repository\Listeners;

use Illuminate\Support\Facades\Log;
use Illuminate\Database\Eloquent\Model;
use Dipper\Foundation\Repository\CacheKeys;
use Dipper\Foundation\Repository\RepositoryInterface;
use Dipper\Foundation\Repository\Events\RepositoryEventBase;
use Illuminate\Contracts\Cache\Repository as CacheRepository;

/**
 * Class CleanCacheRepository.
 */
class CleanCacheRepository
{
    /**
     * @var CacheRepository
     */
    protected $cache = null;

    /**
     * @var RepositoryInterface
     */
    protected $repository = null;

    /**
     * @var Model
     */
    protected $model = null;

    /**
     * @var string
     */
    protected $action = null;

    /**
     *
     */
    public function __construct()
    {
        $this->cache = app(config('dipper.repository.cache.repository', 'cache'));
    }

    /**
     * @param RepositoryEventBase $event
     */
    public function handle(RepositoryEventBase $event)
    {
        try {
            $this->repository = $event->getRepository();
            $this->model = $event->getModel();
            $this->action = $event->getAction();

            if (CacheKeys::isTaggable($this->cache)) {
                $this->cache->tags(get_class($this->repository))->flush();
            } else {
                $cacheKeys = app(CacheKeys::class)->getKeys(get_class($this->repository));

                if (is_array($cacheKeys)) {
                    foreach ($cacheKeys as $key) {
                        $this->cache->forget($key);
                    }
                }
            }
        } catch (\Exception $e) {
            Log::error($e->getMessage());
        }
    }
}
