<?php
class ApplicationSettings {
	const SETTINGS_PATH="settings.ini";
	
	private static $DEFAULT_SETTINGS=array(
		"general"=>array(
			"default_page"=>"E404",
			"template"=>"template.php"
		)
	);
	private static $_settings;
	
	private static function PopulateSettingsWithDefaults(){
		if (self::$_settings==null)
			self::$_settings=array();
		
		foreach (self::$DEFAULT_SETTINGS as $category=>$settings){
			if (!isset(self::$_settings[$category]))
				self::$_settings[$category]=self::$DEFAULT_SETTINGS[$category];
			else
				foreach ($settings as $key=>$value)
					if (!isset(self::$_settings[$category][$key]))
						self::$_settings[$category][$key]=$value;
		}
	}
	
	public static function ReloadSettings(){
		if (file_exists(self::SETTINGS_PATH)){
			try {
				self::$_settings=parse_ini_file(self::SETTINGS_PATH,true);
			} catch(Exception $e){
				throw new Exception("Unable to load settings.ini", 0, $e);
			}
		}
		self::PopulateSettingsWithDefaults();	
	}

	public static function GetSetting($category,$setting){
		if (self::$_settings==null)
			self::ReloadSettings();
		
		if (!isset(self::$_settings[$category]))
			throw new Exception("Settings category '$category' has not been defined.");
		if (!isset(self::$_settings[$category][$setting]))
			throw new Exception("Setting '$setting' has not been defined.");
		
		return self::$_settings[$category][$setting];
	}

	public static function GetSettings($category){
		if (self::$_settings==null)
			self::ReloadSettings();
		
		if (!isset(self::$_settings[$category]))
			throw new Exception("Settings category '$category' has not been defined.");
		
		return self::$_settings[$category];
	}
	
	public static function RegisterDefaultSetting($category,$setting,$value){
		if(!isset(self::$DEFAULT_SETTINGS[$category]))
			self::$DEFAULT_SETTINGS[$category]=array();
		self::$DEFAULT_SETTINGS[$category][$setting]=$value;
		self::ReloadSettings();
	}
}
