<?php

class Rtn_Application_Core extends Zend_Application {

	static $config;
	static $loadedRbModels = array();

	public function __construct($environment, $options = null) {
		$this->_environment = (string) $environment;

		if (null !== $options) {
			if (is_string($options)) {
				$options = $this->_loadConfig($options);
				static::$config = $options;
			} else {
				throw new Rtn_Exception_Application('Invalid options provided; must be location of config file');
			}
			$this->setOptions($options->toArray());
		}
	}

	/**
	 * Load configuration file of options
	 *
	 * @param  string $file
	 * @throws Rtn_Exception_Application When invalid configuration file is provided
	 * @return object
	 */
	protected function _loadConfig($file) {
		$environment = $this->getEnvironment();
		$suffix = pathinfo($file, PATHINFO_EXTENSION);
		$suffix = ($suffix === 'dist') ? pathinfo(basename($file, ".$suffix"), PATHINFO_EXTENSION) : $suffix;

		switch (strtolower($suffix)) {
			case 'ini':
				$config = new Zend_Config_Ini($file, $environment);
				break;

			case 'xml':
				$config = new Zend_Config_Xml($file, $environment);
				break;

			case 'json':
				$config = new Zend_Config_Json($file, $environment);
				break;

			case 'yaml':
			case 'yml':
				$config = new Zend_Config_Yaml($file, $environment);
				break;

			case 'php':
			case 'inc':
				$config = include $file;
				if (!is_array($config)) {
					throw new Rtn_Exception_Application('Invalid configuration file provided; PHP file does not return array value');
				}
				return $config;
				break;

			default:
				throw new Rtn_Exception_Application('Invalid configuration file provided; unknown config type');
		}

		return $config;
	}

}
