<?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\CategoryAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Category;
use Newland\Toubiz\Sync\Neos\Domain\Repository\CategoryRepository;

/**
 * Category importer.
 *
 * @Flow\Scope("singleton")
 */
class CategoryImporter extends AbstractImporter
{
    /**
     * @Flow\Inject
     * @var CategoryRepository
     */
    protected $categoryRepository;

    /**
     * Import method.
     *
     * Persist given data by creating new objects or updating existing ones.
     *
     * @param CategoryAdapterInterface $data
     * @return Category
     */
    public function import($data)
    {
        $category = $this->categoryRepository->findOneByOriginalId($data->getExternalId());
        $persisted = !!$category;

        if (!$category) {
            $category = new Category;
        }

        if (!$category->getOriginalId()) {
            $category->setOriginalId($data->getExternalId());
        }
        $category->setTitle($data->getName());

        if ($persisted) {
            $this->categoryRepository->update($category);
        } else {
            $this->categoryRepository->add($category);
        }

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

        return $category;
    }
}
