<?php declare(strict_types=1);
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() ] ]);
        $this->validateTimeRange($data);

        $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());
        $eventDate->setCancelled($data->isCancelled());
        $eventDate->setActive($data->isActive());
        $eventDate->setHasDate($data->hasDate());

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

        return $eventDate;
    }

    /**
     * @param EventDateAdapterInterface $data
     */
    protected function validateTimeRange(EventDateAdapterInterface $data): void
    {
        $beginsAt = $data->getBeginsAt();
        $endsAt = $data->getEndsAt();
        if ($beginsAt === null || $endsAt === null) {
            return;
        }

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