<?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\CityApiService;
use Newland\Toubiz\Api\Service\Toubiz\Legacy\ObjectAdapter\CityApiService\CityAdapter;
use Newland\Toubiz\Sync\Neos\Command\Helper\ApiServiceHelper;
use Newland\Toubiz\Sync\Neos\Command\Helper\ConfigurationHelper;
use Newland\Toubiz\Sync\Neos\Importer\ArticleImporter;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Service\UuidPredictionService;

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

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

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

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

    /** @var string */
    protected static $serviceName = 'Toubiz/Legacy/CityApi';

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

    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 CityApiService $service */
        $service = $this->apiServiceHelper->initializeApiServiceWithCommonConfigurationOptions(
            static::$serviceName,
            $configuration
        );


        $this->processed = 0;
        $this->ids = [];
        $uuidPredictionService = $this->uuidPredictionService(
            (string) $configuration['client'],
            (string) $configuration['language']
        );

        $result = $service->fetchCities(
            $errorHandlerWrapper(
                function (CityAdapter $record, ?int $total) use ($onProgress, $uuidPredictionService, $configuration) {
                    $onProgress(++$this->processed, $total);
                    $importer = new ArticleImporter();
                    $importer->setUuidPredictionService($uuidPredictionService);
                    $importer->setLanguage((string) $configuration['language']);
                    $importer->setClient((string) $configuration['client']);
                    $imported = $importer->import($record);
                    if ($imported) {
                        $this->ids[] = (string) $imported->getPersistenceObjectIdentifier();
                    }
                }
            )
        );

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

    private function uuidPredictionService(string $client, string $language): UuidPredictionService
    {
        $uuidPredictionService = new UuidPredictionService();
        $uuidPredictionService->setDefaultProperties(
            [
                'client' => $client,
                'language' => $language,
                'mainType' => ArticleConstants::TYPE_ATTRACTION,
            ]
        );

        return $uuidPredictionService;
    }

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