<?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\ArticleAdapterInterface;
use Newland\Toubiz\Sync\Neos\Domain\Model\Address;
use Newland\Toubiz\Sync\Neos\Domain\Model\Article;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;

/**
 * Article importer.
 *
 * @Flow\Scope("singleton")
 */
class ArticleImporter extends AbstractImporter
{
    /**
     * @var ArticleAdapterInterface
     */
    protected $data;

    /**
     * @var Article
     */
    protected $article;

    /**
     * @Flow\Inject
     * @var ArticleRepository
     */
    protected $articleRepository;

    /**
     * @var string
     */
    protected $client = '';

    /**
     * @var string
     */
    protected $openingTimesFormat;

    /**
     * @param ArticleAdapterInterface $data
     * @return void
     */
    public function remove(ArticleAdapterInterface $data)
    {
        $this->initialize($data);

        if ($this->article === null) {
            $this->articleRepository->remove($this->article);
            $this->persistenceManager->persistAll();
        }
    }

    /**
     * Import method.
     *
     * Persist given data by creating new objects or updating existing ones.
     *
     * @param ArticleAdapterInterface $data
     * @return void
     */
    public function import($data)
    {
        $this->initialize($data);
        $persisted = $this->article !== null;

        if ($this->article === null) {
            $this->article = new Article();
        }

        $this->mapSimpleValues();
        $this->mapRatingValues();
        $this->article->setClient($this->client);
        $this->mapOpeningTimes();

        if ($persisted) {
            $this->articleRepository->update($this->article);
        } else {
            $this->articleRepository->add($this->article);
        }

        $this->mapAddresses();
        $this->mapCategories();
        $this->mapFiles();
        $this->mapMedia();
        $this->mapAttributes();
        $this->article->setUpdatedAt(new \DateTime);

        $this->articleRepository->update($this->article);
        $this->persistenceManager->persistAll();
    }


    /**
     * @param ArticleAdapterInterface $data
     * @return void
     */
    private function initialize(ArticleAdapterInterface $data)
    {
        $this->data = $data;

        if ($this->client) {
            $article = $this->articleRepository->findOneByOriginalIdAndClient(
                $this->data->getExternalId(),
                $this->client
            );
        } else {
            $article = $this->articleRepository->findOneByOriginalId($this->data->getExternalId());
        }

        if ($article !== null) {
            $this->article = $article;
        }
    }

    /**
     * @param string $client
     */
    public function setClient(string $client)
    {
        $this->client = $client;
    }

    public function setOpeningTimesFormat(string $openingTimesFormat)
    {
        $this->openingTimesFormat = $openingTimesFormat;
    }

    /**
     * Maps simple values onto the article.
     *
     * @return void
     */
    protected function mapSimpleValues()
    {
        if (empty($this->article->getOriginalId())) {
            $this->article->setOriginalId($this->data->getExternalId());
        }

        $this->article->setMainType($this->data->getMainType());
        $this->article->setName($this->data->getName());
        $this->article->setAbstract($this->data->getAbstract());
        $this->article->setDescription($this->data->getDescription());
        $this->article->setFacebookUri($this->data->getFacebookUri());
        $this->article->setTwitterUri($this->data->getTwitterUri());
        $this->article->setInstagramUri($this->data->getInstagramUri());
        $this->article->setYoutubeUri($this->data->getYoutubeUri());
        $this->article->setSourceName($this->data->getSourceName());
        $this->article->setAuthorName($this->data->getAuthorName());
        $this->article->setBookingUri($this->data->getBookingUri());
        $this->article->setDetailUri($this->data->getDetailUri());

        $mainAddressAdapter = $this->data->getMainAddress();
        if ($mainAddressAdapter) {
            $this->article->setMainAddress(
                (new AddressImporter())->import($mainAddressAdapter)
            );
        } else {
            $this->article->setMainAddress(null);
        }
    }

    protected function mapRatingValues()
    {
        $this->article->setStarClassification($this->data->getStarClassification());
        $this->article->setAverageRating($this->data->getAverageRating());
        $this->article->setNumberOfRatings($this->data->getNumberOfRatings());
    }

    /**
     * Maps addresses onto the article.
     *
     * @return void
     */
    protected function mapAddresses()
    {
        $addresses = $this->article->getAddresses();
        $addresses->clear();

        foreach ($this->data->getAddresses() as $address) {
            $importer = new AddressImporter;
            $addresses->add($importer->import($address));
        }
        $this->article->setAddresses($addresses);
    }

    /**
     * Maps categories onto the article.
     *
     * @return void
     */
    protected function mapCategories()
    {
        $categories = $this->article->getCategories();
        $categories->clear();

        if (empty($this->data->getCategories())) {
            return;
        }

        foreach ($this->data->getCategories() as $entry) {
            $importer = new CategoryImporter;
            $category = $importer->import($entry);
            if (!$categories->contains($category)) {
                $categories->add($category);
            }
        }
        $this->article->setCategories($categories);
    }

    /**
     * Maps multimedia items onto the article.
     *
     * @return void
     */
    protected function mapMedia()
    {
        $media = $this->article->getMedia();
        $media->clear();

        if (empty($this->data->getMedia())) {
            return;
        }

        foreach ($this->data->getMedia() as $entry) {
            $importer = new MediumImporter;
            $medium = $importer->import($entry);
            if (!$media->contains($medium)) {
                $media->add($medium);
            }
        }
        $this->article->setMedia($media);
    }

    /**
     * Maps files onto the article.
     *
     * @return void
     */
    protected function mapFiles()
    {
        $files = $this->article->getFiles();
        $files->clear();

        if (empty($this->data->getFiles())) {
            return;
        }

        foreach ($this->data->getFiles() as $entry) {
            $importer = new FileImporter;
            $file = $importer->import($entry);
            if (!$files->contains($file)) {
                $files->add($file);
            }
        }
        $this->article->setFiles($files);
    }

    public function mapOpeningTimes()
    {
        if ($this->openingTimesFormat) {
            $this->article->setOpeningTypeFormat($this->openingTimesFormat);
            $this->article->setOpeningTimes($this->data->getOpeningTimes() ?? '');
        }
    }

    /**
     * @param \DateInterval $timeToLive
     * @return void
     */
    public function deleteOldRecords(\DateInterval $timeToLive)
    {
        $this->articleRepository->deleteOldRecords($timeToLive);
    }

    /**
     * Maps attributes onto the article.
     *
     * @return void
     */
    protected function mapAttributes()
    {
        if (!$this->data->hasAttributes()) {
            return;
        }

        $attributes = $this->article->getAttributes();
        $attributes->clear();

        foreach ($this->data->getAttributes() as $attributeData) {
            $importer = new AttributeImporter();
            $importer->setArticle($this->article);
            $attribute = $importer->import($attributeData);
            if (!$attributes->contains($attribute)) {
                $attributes->add($attribute);
            }
        }

        $this->article->setAttributes($attributes);
    }
}
