<?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
     * @param EventDate|null $eventDate
     * @return EventDate
     */
    public function import($data, ?EventDate $eventDate = null)
    {
        $persisted = (bool) $eventDate;
        $eventDate = $eventDate ?? new EventDate();

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

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

        return $eventDate;
    }
}
