<?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\MediumAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Event;
use Newland\Toubiz\Sync\Neos\Domain\Model\Medium;
use Newland\Toubiz\Sync\Neos\Domain\Repository\MediumRepository;

/**
 * Medium importer.
 *
 * @Flow\Scope("singleton")
 */
class MediumImporter extends AbstractImporter
{
    /**
     * @var Event
     */
    protected $event;

    /**
     * @Flow\Inject
     * @var MediumRepository
     */
    protected $mediumRepository;

    /**
     * @param Event $event
     * @return void
     */
    public function setEvent(Event $event)
    {
        $this->event = $event;
    }

    /**
     * Import method.
     *
     * Persist given data by creating new objects or updating existing ones.
     *
     * @param MediumAdapterInterface $data
     * @return Medium
     */
    public function import($data)
    {
        $medium = $this->mediumRepository->findOneByOriginalId($data->getExternalId());
        $persisted = (bool) $medium;

        if (!$medium) {
            $medium = new Medium();
        }

        if (!$medium->getOriginalId()) {
            $medium->setOriginalId($data->getExternalId());
        }

        $medium->setTitle($data->getTitle());
        $medium->setCopyright($data->getCopyright());
        $medium->setSourceUri($data->getSourceUri());
        $medium->setSorting((int) $data->getSorting());

        if ($persisted) {
            $this->mediumRepository->update($medium);
        } else {
            $this->mediumRepository->add($medium);
        }

        return $medium;
    }
}
