<?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 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
{
    /**
     * @Flow\Inject()
     * @var WeatherRepository
     */
    protected $weatherRepository;

    /**
     * @var Weather
     */
    protected $weather;

    /**
     * @var WeatherAdapterInterface
     */
    protected $data;

    /**
     * @var string
     */
    protected $location;

    /**
     * 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 void
     */
    public function import($locationData): void
    {

        $this->initialize($locationData);
        $persisted = $this->fetchOrCreateNew();
        // The event is being persisted in order to create relations to it.
        if ($persisted) {
            $this->weatherRepository->update($this->weather);
        } else {
            $this->weatherRepository->add($this->weather);
        }

        $this->weather->setUpdatedAt(new \DateTime);

        // Persisting is required due to the API returning the same object multiple times!
        $this->persistenceManager->persistAll();
    }

    private function initialize(WeatherAdapterInterface $locationData): void
    {
        $this->data = $locationData;
        $this->location = $locationData->getLocation();
    }

    private function fetchOrCreateNew(): bool
    {

        $weather = $this->weatherRepository->findByCity($this->location);
        $persisted = (bool) $weather;

        $this->weather = $weather ?? new Weather($this->data);
        $this->weather->setLocation($this->location);
        $this->weather->setOriginalId($this->location);

        return $persisted;
    }
}
