<?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)
    {
        $this->data = $data;
        $category = $this->categoryRepository->withLanguage($this->language, function () {
            return $this->categoryRepository->findOneByOriginalId($this->data->getExternalId());
        });
        $persisted = (bool) $category;

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

        $category->setOriginalId($this->data->getExternalId());
        $category->setTitle($this->data->getName());
        $category->setLanguage($this->language);

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

        return $category;
    }
}
