<?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\ArticleAdapterInterface;
use Newland\Toubiz\Api\Service\Tportal\ApiService;
use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Sync\Neos\Command\Helper\ApiServiceHelper;
use Newland\Toubiz\Sync\Neos\Command\Helper\ConfigurationHelper;
use Newland\Toubiz\Sync\Neos\Importer\ArticleImporter;

class SynchronizeCongressLocationsFromTportal implements SynchronizationTask, ArticleSynchronizationTask
{
    use HandlesClientsForArticles;

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

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

    /** @var array */
    private $ids = [];

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

    protected static $serviceName = 'Tportal/Api';

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

        foreach ($configuration['clients'] as $clientConfig) {
            $clientConfig['detailUri'] = $clientConfig['detailUri'] ?? null;

            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 ApiService $apiService */
        $apiService = $this->apiServiceHelper->initializeApiServiceWithCommonConfigurationOptions(
            static::$serviceName,
            $configuration
        );
        $apiService->setDetailUriTemplate($configuration['detailUri'] ?? null);

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

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