<?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 Newland\Toubiz\Sync\Neos\Logging\LoggerFactory;
use Psr\Log\LoggerInterface;

class ApiServiceHelper
{

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

    public function injectLogger(LoggerFactory $loggerFactory): void
    {
        $this->logger = $loggerFactory->getLogger();
    }

    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);
        }

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

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

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