<?php

namespace core\config;

/**
 * Special configuration, used especialy to store the whole configuration
 */
class GlobalConfiguration
{
	/**
	 * Equivalent to get method of \core\config\Configuration, but load the whole configuration
	 *
	 * @param \string $keys,... Ordered tuple of keys
	 *
	 * @throws \core\config\ConfigException
	 *
	 * @return \core\config\ClassConfiguration
	 */
	public static function read(string ...$keys) : \core\config\ClassConfiguration
	{
		$configuration = self::load();

		$key = \array_shift($keys);

		if (\in_array($key, \get_object_vars($configuration)))
		{
			return $configuration->$key->get(...$keys);
		}

		\throw new \core\config\ConfigException(\core\substitute(
			_('the key {key} does not exist in this part of the configuration'),
			array('key' => $key),
		), 1);
	}

	/**
	 * Get a subpart of this configuration or a value in this configuration
	 *
	 * @param \string $keys,... Ordered tuple of key, which give the address of the wanted part
	 *
	 * @return \bool
	 */
	public static function exists(keys: string ...$keys) : bool
	{
		$configuration = self::load();

		$key = \array_shift($keys);

		if (\in_array($key, \get_object_vars($configuration)))
		{
			return $configuration->$key->exists(...$keys);
		}

		return False;
	}

	/**
	 * Load global configuration
	 *
	 * @return \core\config\GlobalConfigurationState
	 */
	public static function load() : \core\config\GlobalDynamicConfiguration
	{
		try
		{
			if (\class_exists('\\Yosymfony\\Toml\\Toml'))
			{
				$core_config = \Yosymfony\Toml\Toml::ParseFile('config/core.toml'); # NOTE: hard-coded path
				$user_config = \Yosymfony\Toml\Toml::ParseFile('config/config.toml'); # NOTE: hard-coded path
			}
			else
			{
				\throw new \RuntimeException(_('Toml module not found, fallback to parse_ini_file'))
			}
		}
		catch (\RuntimeException)
		{
			$core_config = \parse_ini_file('config/core.toml');
			$user_config = \Yosymfony\Toml\Toml::ParseFile('config/config.toml');
		}

		return new \core\config\GlobalDynamicConfiguration(
			\array_merge($core_config, $user_config),
		);
	}
}

?>