<?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\EventTagAdapterInterface;
use Newland\Toubiz\Api\Service\Toubiz\Legacy\ObjectAdapter\EventApiService\EventTagAdapter;
use Newland\Toubiz\Sync\Neos\Domain\Model\EventTag;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventTagRepository;

class EventTagImporter extends AbstractImporter
{
    /**
     * @Flow\Inject()
     * @var EventTagRepository
     */
    protected $eventTagRepository;

    /** @var EventTag */
    protected $eventTag;

    /**
     * Import method.
     *
     * Persist given data by creating new objects or updating existing ones.
     *
     * @param EventTagAdapterInterface $data
     * @return EventTag
     */
    public function import($data)
    {
        $tag = $this->fetchEventTag($data);
        $persisted = (bool) $tag;
        $this->eventTag = $tag ?? new EventTag();

        if (!$this->eventTag->getOriginalId()) {
            $this->eventTag->setOriginalId($data->getKeywordTypeId());
        }

        $this->eventTag->setKeyword($data->getKeyword());
        $this->eventTag->setLanguage($this->language);

        if ($persisted) {
            $this->eventTagRepository->update($this->eventTag);
        } else {
            $this->eventTagRepository->add($this->eventTag);
        }

        return $this->eventTag;
    }

    private function fetchEventTag(EventTagAdapterInterface $eventTagAdapter): ?EventTag
    {

        return $this->eventTagRepository->withLanguage(
            $this->language,
            function () use ($eventTagAdapter) {
                return $this->eventTagRepository->findOneByOriginalId(
                    $eventTagAdapter->getKeywordTypeId()
                );
            }
        );
    }
}
