<?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\Sync\Neos\Domain\Model\EventTag;
use Newland\Toubiz\Sync\Neos\Domain\Repository\EventTagRepository;

/**
 * Event Tag importer.
 *
 * @Flow\Scope("singleton")
 */
class EventTagImporter extends AbstractImporter
{
    /**
     * @Flow\Inject()
     * @var EventTagRepository
     */
    protected $eventTagRepository;

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

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

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

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

        return $eventTag;
    }
}
