<?php

/**
 * Goweb_Form_Element_Select
 *
 * @category    Goweb
 * @package     Goweb_Form
 * @subpackage  Element
 * @version     5.0.24
 * @author      I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright   2010 (c) Goweb (http://www.goweb.pt)
 */

/**
 * Goweb_Form_Element
 */
Goweb::loadClass('Goweb_Form_Element_Select');

/**
 * Classe para representar um elemento do tipo Combo-box
 *
 * @version     5.0.25
 * @category    Goweb
 * @package     Goweb_Form
 * @subpackage  Element
 * @author      I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright   2010 (c) Goweb (http://www.goweb.pt)
 */
class Goweb_Form_Element_Combo extends Goweb_Form_Element_Select {
    protected $_registerInArrayValidator = false;

    /**
     * Contructor
     *
     * Parâmetros extra:
     *
     * disabled => (bool)   TRUE se o elemento for desabilitado
     * size     => (string) Número de linhas
     * multiple => (bool)   TRUE se for de multipla escolha
     * options  => (array)  Array com as opções no formato $key => $label
     *
     * @param  array  $options  opções de configuração
     */
    public function __construct($options = array()) {
        $this->_config['type'] = 'combo';
        $this->_config['disabled'] = false;
        $this->_config['db_type']          = null;
        $this->_config['db_host']          = null;
        $this->_config['db_user']          = null;
        $this->_config['db_pass']          = null;
        $this->_config['db_name']          = null;
        $this->_config['db_table']         = null;
        $this->_config['db_table_value']   = null;
        $this->_config['db_table_desc']    = null;
        $this->_config['clausulas_extras'] = null;
        $this->_config['options'] = array();
        $this->_config['sql'] = '';
        parent::__construct($options);
    }

    /**
     * Este metodo adiciona directamente uma opção es opções do select.
     *
     * @param   string  $key     O valor da chave
     * @param   array   $label   O label a ser mostrado
     * @throws  Goweb_Exception  Se o a chave já existir nas opções do elemento 
     */
    public function _addOptionCombo() {
        $this->_config['sql'] = '';
        $this->_config['sql'] .= 'SELECT ' . $this->_config['db_table_value'] . ', ';
        $this->_config['sql'] .= $this->_config['db_table_desc'] . ' FROM ';
        $this->_config['sql'] .= $this->_config['db_table'];

        /**
         * @see Zend_Db_Adapter_Abstract
         */
        $db = $this->_getDb();
        if ($db){
            $result = $db->query($this->_config['sql']);
            if ($result){
                foreach ($result as $row){
                    $this->addOption($row[$this->_config['db_table_value']], $row[$this->_config['db_table_desc']]);
                }
            }
        }
    }

    public function getDescFromValue($value = null){
        $this->_config['sql'] = '';
        $this->_config['sql'] .= 'SELECT ' . $this->_config['db_table_value'] . ', ';
        $this->_config['sql'] .= $this->_config['db_table_desc'] . ' FROM ';
        $this->_config['sql'] .= $this->_config['db_table'];
        /**
         * @see Zend_Db_Adapter_Abstract
         */
        $db = $this->_getDb();
        if (stripos($this->_config['clausulas_extras'], 'where')){
            $this->_config['clausulas_extras'] = str_ireplace('where', 'WHERE ' . $this->_config['db_table_value'] . '=' . $db->quote($value) . ' AND ', $this->_config['clausulas_extras']);
        } else {
            $this->_config['clausulas_extras'] = ' WHERE ' . $this->_config['db_table_value'] . '=' . $db->quote($value) . ' ' . $this->_config['clausulas_extras'];
        }
        if (!is_null($this->_config['clausulas_extras'])) {
            $this->_config['sql'] .= ' ' . $this->_config['clausulas_extras'];
        }

        if ($db){
            $result = $db->query($this->_config['sql']);
            if ($result){
                foreach ($result as $row){
                    return $row[$this->_config['db_table_desc']];
                }
            }
        }
    }

    /**
     * Obter o adapter para a ligação
     *
     * @return Zend_Db_Adapter_Abstract
     */
    protected function _getDb(){
        $db = null;
        switch ($this->_config['db_type']) {
            case 'mysql':
                // a base de dados eh MySql
                $db = $this->_getMySqlConnection();
                break;
            case 'mssql':
                // a base de dados eh MS SQL Server
                $db = $this->_getMSSqlConnection();
                break;
            case 'oracle':
                // a base de dados eh Oracle
                $db = $this->_getOracleConnection();
                break;
        }
        return $db;
    }

    /**
     * Obter a ligação à base de dados MySQL 
     *
     * @return Zend_Db_Adapter_Abstract
     */
    protected function _getMySqlConnection() {
        $db = null;
        $config = array('host' => $this->_config['db_host'],
                        'username' => $this->_config['db_user'],
                        'password' => $this->_config['db_pass'],
                        'dbname' => $this->_config['db_name'],
                        'charset' => str_replace('-', '', CHARSET));
        try {
            $db = Zend_Db::factory('pdo_' . $this->_config['db_type'], $config);
        } catch (Exception $e) {

        }

        if (!$db){
            try {
                $db = Zend_Db::factory($this->_config['db_type'] . 'i', $config);
            } catch (Exception $e) {

            }

        }
        return $db;
    }

    /**
     * Obter a ligação à base de dados Oracle 
     *
     * @return Zend_Db_Adapter_Abstract
     */
    protected function _getOracleConnection() {
        $db = null;
        $config = array('host' => $this->_config['db_host'],
                        'username' => $this->_config['db_user'],
                        'password' => $this->_config['db_pass'],
                        'dbname' => $this->_config['db_name'],
                        'charset' => str_replace('-', '', CHARSET));
        try {
            $db = Zend_Db::factory('pdo_oci', $config);
        } catch (Exception $e) {

        }

        if (!$db){
            try {
                $db = Zend_Db::factory('Oracle', $config);
            } catch (Exception $e) {

            }

        }
        return $db;
    }

    /**
     * Obter a ligação à base de dados MSSql 
     *
     * @return Zend_Db_Adapter_Abstract
     */
    protected function _getMSSqlConnection() {
        $db = null;
        $config = array('host' => $this->_config['db_host'],
                        'username' => $this->_config['db_user'],
                        'password' => $this->_config['db_pass'],
                        'dbname' => $this->_config['db_name'],
                        'charset' => str_replace('-', '', CHARSET));
        try {
            $db = Zend_Db::factory('pdo_' . $this->_config['db_type'], $config);
        } catch (Exception $e) {

        }

        if (!$db){
            try {
                $db = Zend_Db::factory('Sqlsrv', $config);
            } catch (Exception $e) {

            }

        }
        return $db;
    }

    /**
     * Render form element
     *
     * @param  Zend_View_Interface $view
     * @return string
     */
    public function render() {
        $this->_addOptionCombo();
        return parent::render();
    }
}