<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Importer;

use Newland\Toubiz\Api\ObjectAdapter\StarRatingAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\StarClassification;
use Newland\Toubiz\Sync\Neos\Domain\Repository\StarClassificationRepository;
use Neos\Flow\Annotations as Flow;

class StarClassificationImporter extends AbstractImporter
{

    /**
     * @var StarClassificationRepository
     * @Flow\Inject()
     */
    protected $starClassificationRepository;

    /**
     * @param StarRatingAdapterInterface $data
     * @return StarClassification
     */
    public function import($data)
    {
        $this->initializeLogger($data, [
            'starClassification' => [
                'externalId' => $data->getExternalId(),
                'label' => $data->getLabel(),
            ]
        ]);

        /** @var StarClassification|null $classification */
        $classification = $this->starClassificationRepository->withLanguage($this->language, function () use ($data) {
            return $this->starClassificationRepository->findOneBy([ 'originalId' => $data->getExternalId() ]);
        });

        $new = false;
        if ($classification === null) {
            $classification = new StarClassification();
            $new = true;
        }

        $this->mapSimpleValues($classification, $data);

        if ($new) {
            $this->starClassificationRepository->add($classification);
            $this->persistenceManager->persistAll();
        } else {
            $this->starClassificationRepository->update($classification);
        }

        return $classification;
    }

    private function mapSimpleValues(StarClassification $classification, StarRatingAdapterInterface $data): void
    {
        $classification->setOriginalId($data->getExternalId());
        $classification->setBadgeUrl($data->getBadgeUrl());
        $classification->setLabel($data->getLabel());
        $classification->setValue($data->getValue());
        $classification->setLanguage($this->language);
    }
}
