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

    /**
     * @param EventDateAdapterInterface $data
     */
    public function import($data, ?EventDate $eventDate = null): ?EventDate
    {
        $this->initializeLogger($data, [ 'eventDate' => [ 'externalId' => $data->getExternalId() ] ]);

        if ($data->getEndsAt()->getTimestamp() <= $data->getBeginsAt()->getTimestamp()) {
            $this->warning(sprintf(
                'EndTime[%s] is not after StartTime[%s]. This may lead to this date not being visible in lists',
                $data->getEndsAt()->format('Y-m-d H:i:s'),
                $data->getBeginsAt()->format('Y-m-d H:i:s')
            ));
        }

        $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;
    }
}
