<?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;

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
     * @param Medium|null $medium
     * @return Medium
     */
    public function import($data, Medium $medium = null)
    {
        $persisted = (bool) $medium;

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

        $medium->setOriginalId($data->getExternalId());
        $medium->setTitle($data->getTitle());
        $medium->setCopyright($data->getCopyright());
        $medium->setSourceUri($data->getSourceUri());

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

        return $medium;
    }
}
