<?php
namespace Newland\Toubiz\Sync\Neos\Domain\Repository;

/*
 * This file is part of the "toubiz-sync-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Cache\Frontend\FrontendInterface;
use Neos\Flow\Annotations as Flow;
use Neos\Flow\Cache\CacheManager;
use Newland\Toubiz\Api\ObjectAdapter\WeatherAdapterInterface;

/**
 * Weather repository.
 *
 * @Flow\Scope("singleton")
 */
class WeatherRepository
{
    const FORECAST_CACHE = 'forecast';

    /**
     * @Flow\Inject
     * @var CacheManager
     */
    protected $cacheManager;

    /**
     * @var FrontendInterface
     */
    protected $cache;

    /**
     * Instance constructor.
     *
     * @return void
     */
    public function initializeObject()
    {
        $this->cache = $this->cacheManager->getCache('Newland_Toubiz_Sync_Neos-Weather');
    }

    /**
     * Find weather by city.
     *
     * @param string $location
     * @return WeatherAdapterInterface|null
     */
    public function findByCity($location)
    {
        $data = $this->cache->get(self::FORECAST_CACHE);
        if (is_array($data) && array_key_exists($location, $data)) {
            return $data[$location];
        }

        return null;
    }

    /**
     * Find all cities.
     *
     * @return array
     */
    public function findAllCities(): array
    {
        $data = $this->cache->get(self::FORECAST_CACHE);
        if (!$data) {
            return [];
        }
        return array_keys($data);
    }

    /**
     * Stores data to cache.
     *
     * @param mixed $data
     * @return void
     */
    public function store($data)
    {
        $this->cache->set(self::FORECAST_CACHE, $data);
    }
}
