<?php

if(!defined('ONYX')) exit;

class chConfig
{
  //Adresse vers le fichier de configuration en cours de modification
  private $_filename;

  //Le site est-il actif ?
  var $active = 1;

  //Adresse absolue vers le dossier principal
  var $root;

  //Activer le cache ?
  var $cache = 1;

  //Liste des configurations en fonction des fichiers
  var $configs;


  // Constructeur qui charge le fichier de configuration
  function __construct($filename = null)
  {
    if (!empty($filename))
      $this->_filename = $filename;
    else
      $this->_filename = ONYX."config/root.xml";

    //On charge le fichier
    $xml = new DOMDocument();
    $xml->load($this->_filename);

    $this->active = $xml->documentElement->getAttribute('active');
    $this->root = $xml->documentElement->getAttribute('root');
    $this->cache = $xml->documentElement->getAttribute('cache');

    $this->configs = array();
    
    foreach($xml->getElementsByTagName('config') as $value)
      {
	$this->configs[$value->getAttribute('match')] = new __config($value);
      }
  }

  function addConfig($config)
  {
    $this->configs[$config] = new __config();
  }

  function addVar($name, $value, $config = "*")
  {
    $this->configs[$config]->vars[$name] = $value;
  }

  function addEnv($option, $value, $config = "*")
  {
    $this->configs[$config]->envs[$option] = $value;
  }

  function addModule($name, $config = "*")
  {
    $this->configs[$config]->modules[$name] = array();
  }

  function addModuleOption($moduleName, $name, $value, $config = "*")
  {
    $this->configs[$config]->modules[$moduleName][$name] = $value;
  }

  //Fonction qui écrit le fichier
  function write()
  {
    $xml = new DOMDocument('1.0', 'UTF-8');
    $xml->formatOutput = true;

    $xml_configs = $xml->createElement("configs");
    $xml_configs->setAttribute("active", $this->active);
    $xml_configs->setAttribute("root", $this->root);
    $xml_configs->setAttribute("cache", $this->cache);

    foreach($this->configs as $match => $config)
      {
	$xml_config = $xml->createElement("config");
	$xml_config->setAttribute("match", $match);

	//On écrit les variables
	chConfig::unparse_config($xml, $xml_config, $config->vars, "var", "name");
	chConfig::unparse_config($xml, $xml_config, $config->envs, "env", "option");

	//On écrit les modules
	if (is_array($config->modules))
	  foreach($config->modules as $mod_name => $module)
	    {
	      $xml_module = $xml->createElement("module");
	      $xml_module->setAttribute("name", $mod_name);
	      chConfig::unparse_config($xml, $xml_module, $module, "option", "name");
	      $xml_config->appendChild($xml_module);
	    }

	$xml_configs->appendChild($xml_config);
      }

    $xml->appendChild($xml_configs);

    $xml->save($this->_filename);
  }
}
?>