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

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->initializeLogger($data, [
            'category' => [
                'name' => $data->getName(),
                'externalId' => $data->getExternalId(),
            ]
        ]);

        $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 ($data instanceof HasLanguageGroupingSeparateFromOriginalId) {
            $category->setLanguageGrouping($data->getLanguageGrouping());
        } else {
            $category->setLanguageGrouping($data->getExternalId());
        }


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

        return $category;
    }
}
