<?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\Api\ObjectAdapter\EventTagAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Event;
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
     * @return EventTag
     */
    public function import($data)
    {
        $eventTag = $this->eventTagRepository->findOneByOriginalId($data->getKeywordTypeId());
        $persisted = (bool) $eventTag;

        if (!$eventTag) {
            $eventTag = new EventTag;
        }

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

        $eventTag->setKeyword($data->getKeyword());

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

        // Persisting is required due to the API returning the same object multiple times!
        $this->persistenceManager->persistAll();

        return $eventTag;
    }
}
