<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Importer;

use Newland\Toubiz\Api\ObjectAdapter\KitchenTimeAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\OpeningTimes\KitchenTime;
use Newland\Toubiz\Sync\Neos\Domain\Repository\OpeningTimes\KitchenTimeRepository;
use Neos\Flow\Annotations as Flow;

class KitchenTimeImporter extends AbstractImporter
{

    /**
     * @var KitchenTimeRepository
     * @Flow\Inject()
     */
    protected $kitchenTimeRepository;

    /**
     * @param KitchenTimeAdapterInterface $data
     */
    public function import($data)
    {
        $this->initializeLogger($data, [
            'kitchenTime' => [ 'originalId' => $data->getExternalId() ]
        ]);

        $kitchenTime = $this->kitchenTimeRepository->findOneByOriginalId($data->getExternalId());
        $isNew = $kitchenTime === null;

        $kitchenTime = $kitchenTime ?? new KitchenTime();

        $kitchenTime->setOriginalId($data->getExternalId());
        $kitchenTime->setFrom($data->getFrom());
        $kitchenTime->setTo($data->getTo());
        $kitchenTime->setComment($data->getComment());
        $kitchenTime->setSorting($data->getSorting());

        if ($isNew) {
            $this->kitchenTimeRepository->add($kitchenTime);
        } else {
            $this->kitchenTimeRepository->update($kitchenTime);
        }

        return $kitchenTime;
    }
}
