<?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
{
    use HandlesClientsForArticles;

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

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

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

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

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

    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 $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($configuration['client'], $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($configuration['language']);
                    $importer->setClient($configuration['client']);
                    $this->ids[] = (string) $importer->import($record)->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;
    }
}
