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

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

class OfferImporter extends AbstractImporter
{

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


    public function import($data): Offer
    {
        $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);
        $this->mapMedia($offer, $data);

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

        return $offer;
    }

    private function mapSimpleValues(Offer $offer, OfferAdapterInterface $data): void
    {
        $offer->setOriginalId($data->getExternalId());
        $offer->setName($data->getName());
        $offer->setStartingPrice($data->getStartingPrice() ?? 0.0);
        $offer->setStartingPriceCurrency($data->getStartingPriceCurrency() ?? '');
        $offer->setDurationMinutes($data->getDurationMinutes() ?? 0);
        $offer->setAddress($data->getAddress() ?? '');
        $offer->setDetailUri($data->getDetailUri());
    }

    private function mapMedia(Offer $offer, OfferAdapterInterface $data): void
    {
        $importer = new MediumImporter();
        $importer->setDownload($this->packageConfig['downloadImages']['offers'] ?? true);
        $importer->loggingContext($this->mergeLoggingContext([
             'offerId' => $data->getExternalId(),
             'offerName' => $data->getName(),
         ]));

        $this->updateCollection(
            $offer->getMedia(),
            $data->getMedia(),
            function (MediumAdapterInterface $adapter) use ($importer) {
                return $importer->import($adapter);
            }
        );
    }
}
