<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Importer;

use Newland\Toubiz\Api\ObjectAdapter\UriAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Uri;
use Newland\Toubiz\Sync\Neos\Domain\Repository\UriRepository;
use Neos\Flow\Annotations as Flow;

class UriImporter extends AbstractImporter
{

    /**
     * @var UriRepository
     * @Flow\Inject()
     */
    protected $uriRepository;

    /**
     * @param UriAdapterInterface $data
     */
    public function import($data): Uri
    {
        /** @var Uri|null $uri */
        $uri = $this->uriRepository->findOneBy([ 'originalId' => $data->getExternalId() ]);
        $isNew = $uri === null;
        $uri = $uri ?? new Uri();

        $uri->setOriginalId($data->getExternalId());
        $uri->setLabel($data->getLabel());
        $uri->setUri($data->getUri());

        if ($isNew) {
            $this->uriRepository->add($uri);
        } else {
            $this->uriRepository->update($uri);
        }

        return $uri;
    }
}
