<?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\Service\Toubiz\Legacy\DirectMarketerApiService;
use Newland\Toubiz\Api\Service\Toubiz\Legacy\ObjectAdapter\DirectMarketerApiService\DirectMarketerAdapter;
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 SynchronizeDirectMarketerFromLegacyToubiz implements SynchronizationTask, DeletesOld, ArticleSynchronizationTask
{
    use HandlesClientsForArticles;

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

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

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

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

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

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

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

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

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

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

    public function deleteOld(SynchronizationResult $result, array $configuration, \Closure $onProgress): void
    {
        $where = [];

        $client = $configuration['client'] ?? null;
        if ($client) {
            $where['client'] = $client;
        }

        $this->articleRepository->setLanguage($configuration['language'] ?? null);
        foreach ($result->getOriginalIdsToDelete() ?? [] as $index => $id) {
            $where['originalId'] = $id;
            $deleted = $this->articleRepository->removeOneWhere($where);

            if ($deleted) {
                $onProgress($index, null);
            }
        }
    }
}
