<?php
namespace Newland\Toubiz\Sync\Neos\Service;

/*
 * This file is part of the "toubiz-brochures-neos" package.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

use Neos\Flow\Annotations as Flow;
use Newland\Toubiz\Api\ObjectAdapter\BrochureAdapterInterface;
use Newland\Toubiz\Api\Service\ServiceFactory;
use Newland\Toubiz\Api\Service\Toubiz\Brochures\ApiService;
use Newland\Toubiz\Sync\Neos\Domain\Model\Brochure;
use Newland\Toubiz\Sync\Neos\Domain\Model\BrochureFilterConfiguration;

class BrochureImportService
{
    /**
     * @var array
     * @Flow\InjectConfiguration(package="Newland.Toubiz.Sync.Neos.services.Toubiz/Brochures/Api")
     */
    protected $configuration;

    public function import($client)
    {
        return $this->service($client)->fetchBrochureList(
            function (BrochureAdapterInterface $adapter) {
                return (new Brochure())->fillFromAdapter($adapter);
            }
        );
    }

    public function getFilterConfiguration(string $client): BrochureFilterConfiguration
    {
        return new BrochureFilterConfiguration($this->service($client)->fetchBrochureConfiguration());
    }

    private function service(string $client): ApiService
    {
        $config = $this->configuration['clients'][$client] ?? null;
        if ($config === null) {
            throw new \InvalidArgumentException(
                sprintf(
                    'Client %s is not configured in "Newland.Toubiz.Sync.Neos.services.Toubiz/Brochures/Api"',
                    $client
                )
            );
        }

        /** @var ApiService $service */
        $service = ServiceFactory::get('Toubiz/Brochures/Api');
        $service->setApiKey($config['apiKey']);
        $service->setClientName($client);
        $service->setParameters([ 'client' => $client ]);

        return $service;
    }
}
