<?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\EventDateAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Event;
use Newland\Toubiz\Sync\Neos\Domain\Model\EventDate;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventDateRepository;

/**
 * Event date importer.
 *
 * @Flow\Scope("singleton")
 */
class EventDateImporter extends AbstractImporter
{
    /**
     * @var Event
     */
    protected $event;

    /**
     * @Flow\Inject
     * @var EventDateRepository
     */
    protected $eventDateRepository;

    /**
     * @param Event $event
     * @return void
     */
    public function setEvent(Event $event)
    {
        $this->event = $event;
    }

    /**
     * Import method.
     *
     * Persist given data by creating new objects or updating existing ones.
     *
     * @param EventDateAdapterInterface $data
     * @return EventDate
     */
    public function import($data)
    {
        $this->initialize($data);

        $eventDate = $this->eventDateRepository->findOneByOriginalId($this->data->getExternalId());
        $persisted = (bool) $eventDate;

        if (!$eventDate) {
            $eventDate = new EventDate();
        }

        if (!$eventDate->getOriginalId()) {
            $eventDate->setOriginalId($this->data->getExternalId());
        }

        $eventDate->setEvent($this->event);
        $eventDate->setBeginsAt($this->data->getBeginsAt());
        $eventDate->setEndsAt($this->data->getEndsAt());
        $eventDate->setNote($this->data->getNote());
        $eventDate->setLanguage($this->language);
        $eventDate->setDetailUri($this->data->getDetailUri());

        if ($persisted) {
            $this->eventDateRepository->update($eventDate);
        } else {
            $this->eventDateRepository->add($eventDate);
        }

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

        return $eventDate;
    }

    private function initialize($data): void
    {
        $this->data = $data;
        $this->eventDateRepository->setLanguage($this->language);
    }
}
