<?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\FileAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\File;
use Newland\Toubiz\Sync\Neos\Domain\Repository\FileRepository;

class FileImporter extends AbstractImporter
{
    /**
     * @Flow\Inject()
     * @var FileRepository
     */
    protected $fileRepository;

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

        if (!$file) {
            $file = new File();
        }

        $file->setOriginalId($data->getExternalId());
        $file->setName($data->getName());
        $file->setSourceUri($data->getSourceUri());

        if ($persisted) {
            $this->fileRepository->update($file);
        } else {
            $this->fileRepository->add($file);
        }

        return $file;
    }
}
