<?php

/**
 * Description of Option
 *
 * @author Mohammed Osman  <osmancode@gmail.com>
 */
class OptionsManager extends CApplicationComponent {

    /**
     * WebSite Options
     * array of {@link Option}
     * @var array
     */
    private $_optionsList;

    /**
     * Active Languages
     * array of {@link CLocale}.
     * @var array
     */
    private $_activeLanguages;

    public function init() {
        parent::init();
        Yii::app()->name = $this->get('SITE_TITLE', Yii::app()->name);
        Yii::app()->language = $this->get('I18N_DEFAULT_LANGUAGE', 'xxx');
//	$defaultLanguage = $this->getDefaultLanguage();
        Yii::app()->timeZone = $this->get('I18N_TIMEZONE', date_default_timezone_get());
    }

    public function findAll() {
        if ($this->_optionsList !== null) {
            return $this->_optionsList;
        } else {
            return $this->_optionsList = Option::model()->findAll();
        }
    }

    public function get($key, $default = '') {
        $options = CHtml::listData($this->findAll(), 'key', 'value');
        if (is_array($options) && isset($options[$key])) {
            return $options[$key];
        } else {
            return $default;
        }
    }

    public function getGroup($groupKey) {
        $options = CHtml::listData($this->findAll(), 'key', 'value', 'group');
        if (is_array($options) && isset($options[$groupKey])) {
            return $options[$groupKey];
        } else {
            return $default;
        }
    }

    public function getActiveLanguages() {

        Yii::import('admin.modules.fmessage.models.Locale');
        if ($this->_activeLanguages !== null) {
            return $this->_activeLanguages;
        } else {
            return $this->_activeLanguages = FlexLocale::model()->findAllByAttributes(array('active' => 1));
        }
    }

    public function getDefaultLanguage() {
        $languages = $this->getActiveLanguages();
        $defaultLanguage = false;
        foreach ($languages as $language) {
            if ($language->default == 1) {
                $defaultLanguage = $language->locale;
            }
        }

        return $defaultLanguage;
    }

}
