<?php declare(strict_types=1);

namespace Newland\Toubiz\Sync\Neos\Command\Task;

use Newland\Toubiz\Api\ObjectAdapter\ArticleAdapterInterface;
use Newland\Toubiz\Api\Service\Toubiz\Legacy\TourApiService;
use Newland\Toubiz\Sync\Neos\Command\Helper\ApiServiceHelper;
use Newland\Toubiz\Sync\Neos\Command\Helper\ConfigurationHelper;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Importer\ArticleImporter;

class SynchronizeToursFromLegacyToubiz implements SynchronizationTask
{

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

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

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

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

    public function configurations(ConfigurationHelper $configurationHelper): \Generator
    {
        $configuration = $configurationHelper->getConfigurationForService('Toubiz/Legacy/TourApi');
        if (!$configuration) {
            return;
        }

        foreach ($configuration['clients'] as $clientConfig) {
            $configuration['client'] = $clientConfig['client'];
            $configuration['apiKey'] = $clientConfig['apiKey'];
            foreach ($clientConfig['languages'] ?? $configuration['languages'] ?? [ 'de' ] as $language) {
                $configuration['language'] = $language;
                yield $configuration;
            }
        }
    }

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

        /** @var TourApiService $service */
        $service = $this->apiServiceHelper->initializeApiServiceWithCommonConfigurationOptions(
            'Toubiz/Legacy/TourApi',
            $configuration
        );

        $this->ids = [];
        $this->processed = 0;
        $result = $service->fetchTours(
            $errorHandlerWrapper(
                function(ArticleAdapterInterface $adapter, ?int $total) use ($onProgress, $configuration) {
                    $importer = new ArticleImporter();
                    $importer->setLanguage($configuration['language']);
                    $imported = $importer->import($adapter);
                    $this->ids[] = (string) $imported->getPersistenceObjectIdentifier();
                    $onProgress(++$this->processed, $total);
                }
            )
        );

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

}
