<?php declare(strict_types=1);
namespace Newland\Toubiz\Sync\Neos\Command\Task;

/*
 * 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 Newland\Toubiz\Api\Constants\Language;
use Newland\Toubiz\Api\ObjectAdapter\Concern\ArticleConstants;
use Newland\Toubiz\Api\Service\Toubiz\Legacy\GastronomyApiService;
use Newland\Toubiz\Api\Service\Toubiz\Legacy\ObjectAdapter\GastronomyApiService\GastronomyAdapter;
use Newland\Toubiz\Sync\Neos\Command\Helper\ApiServiceHelper;
use Newland\Toubiz\Sync\Neos\Command\Helper\ConfigurationHelper;
use Newland\Toubiz\Sync\Neos\Domain\Repository\ArticleRepository;
use Newland\Toubiz\Sync\Neos\Importer\ArticleImporter;
use Neos\Flow\Annotations as Flow;

class SynchronizeGastronomyFromLegacyToubiz implements SynchronizationTask, DeletesOld, ArticleSynchronizationTask
{
    use HandlesClientsForArticles;

    /**
     * @var ApiServiceHelper
     * @Flow\Inject()
     */
    protected $apiServiceHelper;

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

    /** @var string[] */
    protected $ids = [];

    /** @var int */
    protected $processed = 0;

    protected static $serviceName = 'Toubiz/Legacy/GastronomyApi';

    public function name(): string
    {
        return 'Gastronomy';
    }

    public function configurations(ConfigurationHelper $configurationHelper): \Generator
    {
        $configuration = $configurationHelper->getConfigurationForService(static::$serviceName);
        if (!$configuration) {
            return;
        }

        foreach ($configuration['clients'] as $clientKey => $clientConfig) {
            $clientConfig['client'] = (string) ($clientConfig['client'] ?? $clientKey);
            foreach ($clientConfig['languages'] ?? $configuration['languages'] ?? [ Language::DE ] as $language) {
                $clientConfig['language'] = $language;
                yield $configurationHelper->mergeWithDefaults($clientConfig);
            }
        }
    }


    public function synchronize(
        array $configuration,
        \Closure $errorHandlerWrapper,
        \Closure $onProgress
    ): SynchronizationResult {

        /** @var GastronomyApiService $apiService */
        $apiService = $this->apiServiceHelper->initializeApiServiceWithCommonConfigurationOptions(
            static::$serviceName,
            $configuration
        );

        $this->processed = 0;
        $this->ids = [];
        $result = $apiService->fetchGastronomy(
            $errorHandlerWrapper(
                function (GastronomyAdapter $record, ?int $total) use ($onProgress, $configuration) {
                    $onProgress(++$this->processed, $total);

                    $importer = new ArticleImporter();
                    $importer->setLanguage($configuration['language']);
                    $importer->setClient($configuration['client']);
                    if ($record->getOnlineStatus()) {
                        $imported = $importer->import($record);
                        if ($imported) {
                            $this->ids[] = (string) $imported->getPersistenceObjectIdentifier();
                        }
                    } else {
                        $importer->remove($record);
                    }
                }
            )
        );

        return SynchronizationResult::fromServiceResult($result, $this->ids);
    }

    public function deleteOld(SynchronizationResult $result, array $configuration, \Closure $onProgress): void
    {
        $this->articleRepository->removeBasedOnSynchronizationResult(
            $result,
            ArticleConstants::TYPE_GASTRONOMY,
            $configuration['client'],
            $configuration['language'],
            $onProgress
        );
    }
}
