<?php declare(strict_types=1);

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

use Neos\Flow\Log\PsrLoggerFactoryInterface;
use Newland\Toubiz\Api\Service\AbstractService;
use Newland\Toubiz\Api\Service\ServiceFactory;
use Psr\Log\LoggerInterface;

class ApiServiceHelper
{

    /**
     * @var LoggerInterface
     */
    protected $logger;

    public function injectLogger(PsrLoggerFactoryInterface $loggerFactory)
    {
        $this->logger = $loggerFactory->get('newlandSyncImport');
    }

    public function initializeApiServiceWithCommonConfigurationOptions(
        string $name,
        array $configuration
    ): AbstractService {
        $service = ServiceFactory::get($name, $configuration['baseUri'] ?? null);

        if (array_key_exists('apiKey', $configuration)) {
            $service->setApiKey($configuration['apiKey']);
        }

        if (method_exists($service, 'setLogger')) {
            $service->setLogger($this->logger);
        }

        $language = $configuration['language'] ?? null;
        if ($language && method_exists($service, 'setLanguage')) {
            $service->setLanguage($language);
        }

        $limit = $configuration['limit'] ?? null;
        if ($limit && method_exists($service, 'setLimit')) {
            $service->setLimit($limit);
        }

        $delta = $configuration['delta'] ?? null;
        if ($delta) {
            $service->setDelta($delta);
        }

        if (array_key_exists('client', $configuration)) {
            $service->setClientName($configuration['client']);
        }

        $service->setParameters($configuration);
        return $service;
    }
}
