<?php

namespace IZON\Admin\DI\Definition\Resolver;


use Exception;

use DI\Definition\Definition;
use DI\Definition\Resolver\DefinitionResolver;

use Interop\Container\ContainerInterface;

use IZON\Admin\Config;
use IZON\Admin\DI\Definition\ModuleConfigsDefinition;

use IZON\Admin\Domain\AdminModuleSetting;

use IZON\Admin\Services\AdminService;

/**
 * 
 */
class ModuleConfigsResolver implements DefinitionResolver
{
    /**
     * @var ContainerInterface
     */
    private $container;

    /**
     * @param Container $container
     */
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    /**
     * Resolve an array definition to a value
     * 
     * @param ModuleConfigsDefinition $definition
     *
     * {@inheritdoc}
     */
    public function resolve(Definition $definition, array $parameters = []) {
        if( ! $definition instanceof ModuleConfigsDefinition ) {
            throw new Exception("Resolved definition must be of class ". ModuleConfigsDefinition::class);
        }
        $adminService = $this->container->get(Config::ADMIN_SERVICE_IDENTIFIER);
        /* @var $adminService AdminService*/
        $settings = $adminService->getModuleSettings($definition->getModuleIdentifier());
        
        $settingsArray = [];
        foreach($settings as $setting) {
            /* @var $setting AdminModuleSetting */
            $settingsArray[$setting->getParamIdentifier()] = $setting->getValue();
        }
        return $settingsArray;
    }

    /**
     * {@inheritdoc}
     */
    public function isResolvable(Definition $definition, array $parameters = []) {
        return true;
    }
}
