<?php

namespace Newland\Toubiz\Sync\Neos\Importer;

/*
 * 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\Flow\Annotations as Flow;
use Neos\Flow\Utility\Now;
use Newland\Toubiz\Api\ObjectAdapter\WeatherAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Weather;
use Newland\Toubiz\Sync\Neos\Domain\Repository\WeatherRepository;

/**
 * Weather importer.
 *
 * This does not fit the rest of the importers as its data
 * is not directly bound to a model nor is the data stored
 * in the database. The whole weather modelling is pragmatic
 * and needs more work in the future!
 *
 * @Flow\Scope("singleton")
 */
class WeatherImporter extends AbstractImporter
{
    /**
     * @var WeatherRepository
     * @Flow\Inject()
     */
    protected $weatherRepository;

    /**
     * @var Now
     * @Flow\Inject(lazy=false)
     */
    protected $now;

    /**
     * Import method.
     *
     * Persist given data by creating new objects or updating existing ones.
     * This takes the whole data response array and stores it in one
     * cache file. Thus, no object adapter exists yet, where data converting
     * should happen instead of the importer itself.
     *
     * @param WeatherAdapterInterface  $locationData
     * @return Weather
     */
    public function import($locationData): Weather
    {
        $weather = $this->fetchOrCreateNew($locationData);

        $weather->setOriginalId($locationData->getExternalId());
        $weather->setLocation($locationData->getLocation());
        $weather->setData($locationData);
        $weather->setUpdatedAt($this->now);

        $this->weatherRepository->store($weather);
        $this->persistenceManager->persistAll();

        return $weather;
    }

    private function fetchOrCreateNew(WeatherAdapterInterface $adapter): Weather
    {
        return $this->weatherRepository->findOneBy([ 'location' => $adapter->getLocation() ])
            ?? new Weather();
    }
}
