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

use Neos\Flow\Configuration\ConfigurationManager;
use Neos\Flow\Configuration\Exception\InvalidConfigurationException;
use Neos\Flow\ObjectManagement\Exception\InvalidObjectException;
use Neos\Flow\ObjectManagement\ObjectManager;
use Newland\Toubiz\Api\Service\GeoLocation\GeoLocationServiceInterface;
use Neos\Flow\Annotations as Flow;

/**
 * @Flow\Scope("singleton")
 */
class GeoLocationFactory
{

    /**
     * @var ConfigurationManager
     * @Flow\Inject
     */
    protected $configuration;

    /**
     * @var ObjectManager
     * @Flow\Inject
     */
    protected $objectManager;

    public function get(string $configurationPath): GeoLocationServiceInterface
    {
        /** @var string|null $class */
        $class = $this->configuration->getConfiguration(
            ConfigurationManager::CONFIGURATION_TYPE_SETTINGS,
            $configurationPath
        );

        if (!\is_string($class) || !\class_exists($class)) {
            throw new InvalidConfigurationException(
                'The configuration ' . $configurationPath . ' must be set to an existing classname ' .
                'but is set to ' . json_encode($class)
            );
        }

        $instance = $this->objectManager->get($class);

        if (!($instance instanceof GeoLocationServiceInterface)) {
            throw new InvalidObjectException(
                'The class referenced in ' . $configurationPath .
                ' ( ' . $class . ') must implement ' . GeoLocationServiceInterface::class
            );
        }


        return $instance;
    }
}
