<?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;

class EventDateImporter extends AbstractImporter
{
    /** @var Event */
    protected $event;

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

    public function setEvent(Event $event): void
    {
        $this->event = $event;
    }

    public function import($data, ?EventDate $eventDate = null): EventDate
    {
        $persisted = (bool) $eventDate;
        $eventDate = $eventDate ?? new EventDate();

        $eventDate->setOriginalId($data->getExternalId());
        $eventDate->setEvent($this->event);
        $eventDate->setBeginsAt($data->getBeginsAt());
        $eventDate->setBeginsAtSpecificTime($data->getBeginsAtSpecificTime());
        $eventDate->setEndsAt($data->getEndsAt());
        $eventDate->setEndsAtSpecificTime($data->getEndsAtSpecificTime());
        $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;
    }
}
