<?php

Goweb::loadClass('Goweb_Form');

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.0
 * @category   library
 * @package    Form
 * @subpackage Generic
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
*/
class Goweb_Form_Generic_Barebone extends Goweb_Form {
    /**
     * Nome do módulo
     *
     * @var string
     */
    protected $_moduleDir = 'Form';

    /**
     * Model a ser usado neste módulo
     *
     * @var string
     */
    protected $_moduleModelElement = 'Form_Model_Element';

    /**
     * Nome do adapter a ser usado neste módulo
     *
     * @var string
     */
    protected $_moduleAdapter = 'db';

    /**
     * Nome do elemento de ligação para este módulo
     *
     * @var string
     */
    protected $_moduleElement = 'form_id';

    /**
     * Metodo obrigatorio as classes herdeiras do Goweb_Form
     */
    public function setup($moduleElementId) {
        if (!is_numeric($moduleElementId)) {
            return $this;
        }
        $moduleConfig = new Goweb_Config(Goweb_Config_Ini::load(APPLICATION_PATH . '/' . $this->_moduleDir . '/config.ini', 'base'));
        $elementModel = Goweb::getModelInstance($this->_moduleModelElement, $this->_moduleAdapter, false);
        $elementModel->where($elementModel->getTableName() . '.' . $this->_moduleElement . '=?', $moduleElementId);
        $elementModel->order('ordem');
        $elements = $elementModel->fetchAll();
        if ($elements) {
            $availableValidators = $elementModel->getValidators();
            foreach ($elements as $element) {
                $name = 'element_' . $element->id;
                $elementType = ucfirst($element->element);
                if (strlen($element->validators)) {
                    $validators = unserialize($element->validators);
					if (is_array($validators) && in_array("Date", $validators)){
						$this->{$name} = $this->Date();
					} else {
					    switch ($elementType) {
					    	case 'Image':
					    	  $this->{$name} = $this->File();
					    	break;
                            case 'Checkbox':
                                $this->{$name} = $this->MultiCheckbox();
                            break;
					    	default:
					    		$this->{$name} = $this->{$elementType}();
					    	break;
					    }
					}
					    
				}else{
                    switch ($elementType) {
                        case 'Image':
                          $this->{$name} = $this->File();
                        break;
                        case 'Checkbox':
                            $this->{$name} = $this->MultiCheckbox();
                        break;
                        default:
                            $this->{$name} = $this->{$elementType}();
                        break;
                    }
				}
                $this->{$name}->label = $element->label;
                if ($element->element == 'text') {
                    if ($element->size > 0) {
                        $this->{$name}->maxlength = $element->size;
                    }
                } elseif ($element->element == 'textarea') {
                    if ($element->rows > 0) {
                        $this->{$name}->rows = $element->rows;
                    }
                    if ($element->cols > 0) {
                        $this->{$name}->cols = $element->cols;
                    }
                } elseif ($element->element == 'checkbox' 
                            || $element->element == 'radio' 
                            || $element->element == 'select') {
                    if (strlen($element->options)) {
                        $options = str_replace(array("\r\n", "\n\r", "\r"), "\n", $element->options);
                        $options = strpos($options, 'a:') === 0 ? unserialize($options) : $options;
                        if (is_array($options)){
                            $elementOptions = array();
                            foreach ($options as $option) {
                                $elementOptions[$option] = $option;
                            }
                            $this->{$name}->options = $elementOptions;
                        } else if (strlen($options)) {
                            $elementOptions = array();
                            /**
                             * Limpar as novas linhas ...
                             * Manter compatibilidade entre os diferentes sistemas
                             * (windows, linux e Mac)
                             * Pedro Pinto
                             */
                            $options=str_replace(array("\r\n", "\n\r", "\r"), "\n", $options);
                            foreach (explode("\n", $options) as $option) {
                                $elementOptions[$option] = $option;
                            }
                            $this->{$name}->options = $elementOptions;
                        }
                        /*if ($elementType == 'Checkbox' && $element->multiple > 0) {
                            $this->{$name}->setIsArray(false);
                        } else if ($element->multiple > 0){
                            $this->{$name}->setIsArray(true);
                        }*/
                        if ($element->element == 'select'){
                            if ($element->rows > 0) {
                                $this->{$name}->size = $element->rows;
                            }
                        }
                    }                    
                } elseif ($element->element == 'combo') {
                    $this->{$name}->db_type          = $element->db_type;
                    $this->{$name}->db_host          = $element->db_host;
                    $this->{$name}->db_user          = $element->db_user;
                    $this->{$name}->db_pass          = $element->db_pass;
                    $this->{$name}->db_name          = $element->db_name;
                    $this->{$name}->db_table         = $element->db_table;
                    $this->{$name}->db_table_value   = $element->db_table_value;
                    $this->{$name}->db_table_desc    = $element->db_table_desc;
                    $this->{$name}->clausulas_extras = $element->clausulas_extras;
                } elseif ($element->element == 'file') {
                    if (!$moduleConfig->files->target) {
                        throw new Goweb_Exception("&Eacute; necess&aacute;rio definir o parametro 'target' com o nome do direct&oacute;rio para efectuar o upload");
                    }
                    if ($moduleConfig->files->max_size) {
                        $this->{$name}->validators->FileSize(translate('O tamanho m&aacute;ximo do ficheiro &eacute; de {{tamanho}} Kb',
                                                                       (ceil($moduleConfig->files->max_size / 1024))),
                                                             array('max_size' => $moduleConfig->files->max_size));
                    }
                    if ($moduleConfig->files->types) {
                         $this->{$name}->validators->FileType(translate('Apenas s&atilde;o v&aacute;lidos ficheiros do tipo "{{tipos}}"', is_array($moduleConfig->files->types) ? implode(', ', $moduleConfig->files->types) : $moduleConfig->files->types),
                                                                 $moduleConfig->files->types);
                    }
                } elseif ($element->element == 'image') {
                    if (!$moduleConfig->images->target) {
                        throw new Goweb_Exception("&Eacute; necess&aacute;rio definir o parametro 'target' com o nome do direct&oacute;rio para efectuar o upload");
                    }
                    
                    $this->{$name}->validators->ImageType(translate('O ficheiro carregado n&atilde;o &eacute; do tipo imagem'));
                                  
                    $this->{$name}->validators->ImageDimensions(translate('As dimen&ccedil;&otilde;es m&aacute;ximas da imagem &eacute; de ') .
                    $moduleConfig->images->original->max_width . 'x' . $moduleConfig->images->original->max_height . ' (pixels)',
                                                                array('max_width'  => $moduleConfig->images->original->max_width,
                                                                      'max_height' => $moduleConfig->images->original->max_height));
                                                                
                    if ($moduleConfig->images->max_size) {
                     $this->{$name}->validators->FileSize(translate('O tamanho m&aacute;ximo do ficheiro &eacute; de') . ' ' . ceil($moduleConfig->images->max_size / 1024) . ' ' . 'Kb',
                                                             array('max_size' => $moduleConfig->images->max_size));
                    }
                    
                }
                // campo obrigat&oacute;rio
                if ($element->required > 0) {
                    $this->{$name}->validators->Required(translate('O campo <b>{{nome}}</b> &eacute; de preenchimento obrigat&oacute;rio.', $this->{$name}->label));
                }
                // validadores
                if (strlen($element->validators)) {
                    $validators = unserialize($element->validators);
                    if (is_array($validators)) {
                        foreach ($validators as $validator) {
                            if (array_key_exists($validator, $availableValidators)) {
                                $this->{$name}->validators->{$validator}(translate('O campo <b>{{nome}}</b> n&atilde;o &eacute; do tipo {{validador}}.', $this->{$name}->label, translate($availableValidators[$validator])));
                            }
                        }
                    }
                }
            }
        }
        return $this;
    }
}