<?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->initialize($data);

        $category = $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;
    }

    private function initialize($data): void
    {
        $this->data = $data;
        $this->categoryRepository->setLanguage($this->language);
    }
}
