<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Importer;

use Newland\Toubiz\Api\ObjectAdapter\AwardAdapterInterface;
use Newland\Toubiz\Api\Service\LanguageAware;
use Newland\Toubiz\Sync\Neos\Domain\Model\Award;
use Newland\Toubiz\Sync\Neos\Domain\Repository\AwardRepository;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Orm\Uuid\UuidGenerator;

class AwardImporter extends AbstractImporter
{
    use LanguageAware;

    /**
     * @var AwardRepository
     * @Flow\Inject
     */
    protected $awardRepository;

    /**
     * @param AwardAdapterInterface $data
     * @return Award|null
     */
    public function import($data)
    {
        $this->initializeLogger($data, [
            'award' => [
                'externalId' => $data->getExternalId(),
            ]
        ]);

        /** @var Award|null $award */
        $award = $this->awardRepository->withLanguage($this->language, function () use ($data) {
            $uuid = UuidGenerator::uuidFromProperties(
                [
                    $data->getExternalId(),
                    $data->getRelatedArticleExternalId(),
                    $this->language
                ]
            )->toString();
            return $this->awardRepository->findByIdentifier($uuid);
        });

        $isNew = $award === null;
        $award = $award ?? new Award();

        $award->setLanguage($this->language);
        $award->setName($data->getName());
        $award->setDescription($data->getDescription());
        $award->setIconName($data->getIconName());
        $award->setImage($data->getImage());
        $award->setOriginalId($data->getExternalId());
        $award->setValue($data->getValue());
        $award->setShowInList($data->getShowInList());
        $award->setValidFrom($data->getValidFrom());
        $award->setValidUntil($data->getValidUntil());
        $award->setRelatedArticleOriginalId($data->getRelatedArticleExternalId());
        $award->setAwardSetName($data->getAwardSetName());

        if ($isNew) {
            $this->awardRepository->add($award);
        } else {
            $this->awardRepository->update($award);
        }

        return $award;
    }
}
