<?php
namespace Newland\Toubiz\Sync\Neos\Importer;

use Newland\Toubiz\Api\ObjectAdapter\OfferAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Offer;
use Newland\Toubiz\Sync\Neos\Domain\Repository\OfferRepository;
use Neos\Flow\Annotations as Flow;

/**
 * @Flow\Scope("singleton")
 */
class OfferImporter extends AbstractImporter
{

    /**
     * @var OfferRepository
     * @Flow\Inject()
     */
    protected $offerRepository;

    /**
     * Main import method.
     *
     * Must be defined in each implementation.
     *
     * @param OfferAdapterInterface $data
     * @return Offer
     * @throws \Neos\Flow\Persistence\Exception\IllegalObjectTypeException
     */
    public function import($data)
    {
        $offer = $this->offerRepository->withLanguage($data->getLanguage(), function () use ($data) {
            return $this->offerRepository->findOneBy([ 'originalId' => $data->getExternalId() ]);
        });
        $isNew = $offer === null;
        $offer = $offer ?? new Offer();

        $offer->setLanguage($data->getLanguage());
        $this->mapSimpleValues($offer, $data);

        if ($isNew) {
            $this->offerRepository->add($offer);
        } else {
            $this->offerRepository->update($offer);
        }

        return $offer;
    }

    /**
     * @param Offer $offer
     * @param OfferAdapterInterface $data
     * @return void
     */
    private function mapSimpleValues(Offer $offer, OfferAdapterInterface $data)
    {
        if (empty($offer->getOriginalId())) {
            $offer->setOriginalId($data->getExternalId());
        }

        $offer->setName($data->getName());
        $offer->setPreviewImage($data->getPreviewImage() ?? '');
        $offer->setStartingPrice($data->getStartingPrice() ?? 0.0);
        $offer->setStartingPriceCurrency($data->getStartingPriceCurrency() ?? '');
        $offer->setDurationMinutes($data->getDurationMinutes() ?? 0);
        $offer->setAddress($data->getAddress() ?? '');
        $offer->setDetailUri($data->getDetailUri());
    }
}
