<?php

Goweb::loadClass('Goweb_Db_Model');

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

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

    /**
     * Model a ser usado neste módulo para os elementos
     *
     * @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';

    /**
     * Nome do segundo elemento de ligação para este módulo (para as fichas)
     *
     * @var string
     */
    protected $_secondModuleElement = null;

    /**
     * Model a ser usado neste módulo
     *
     * @var string
     */
    protected $_secondModuleModel = null;

    /**
     * Nome da Tabela
     *
     * @var string
     */
    protected $_table = 'form_id_';

    /**
     * Chave Primaria
     *
     * @var string
     */
    protected $_primary = 'id';

    /**
     * Campo que sera retornado se um
     * echo do objecto for chamado
     *
     * @var string
     */
    protected $_toString = 'criado';


    /**
     * Metodo obrigatorio. Informa a definicao da tabela
     * referente ao Model em questao.
     */
    protected function _setup() {
        $this->id = $this->Auto();
        if ($this->_secondModuleElement && $this->_secondModuleModel){
            $this->{$this->_moduleElement} = $this->ForeignKey(array('model' => $this->_moduleModel, 'alias' => 'form', 'label' => translate('Ficha')));
            $this->{$this->_secondModuleElement} = $this->ForeignKey(array('model' => $this->_secondModuleModel, 'alias' => 'form', 'label' => 'Liga&ccedil;&atilde;'));
        } else {
            $this->{$this->_moduleElement} = $this->ForeignKey(array('model' => $this->_moduleModel, 'alias' => 'form', 'label' => translate('Formul&aacute;rio')));
        }
        $this->actualizado = $this->Datetime(array('on_update' => '_currentDatetime', 'label' => translate('Actualizado em')));
        $this->criado = $this->Datetime(array('on_insert' => '_currentDatetime', 'label' => translate('Criado em')));
        $this->ip = $this->IpAddress(array('on_update' => '_remoteAddress'));
    }

    public function setup($moduleElementId, $limite = 0){
        if (!is_numeric($moduleElementId)) {
            return $this;
        }
        $elementModel = Goweb::getModelInstance($this->_moduleModelElement, $this->_moduleAdapter, false);
        if (isset($this->_tableFicha) && $this->_tableFicha){
            $this->setTableName($this->_tableFicha . $moduleElementId);
            $this->setTablePrefix($this->_tableFicha. $moduleElementId);
        } else {
            $this->setTableName($this->getTablePrefix() . $moduleElementId);
            $this->setTablePrefix($this->getTablePrefix() . $moduleElementId);
        }
        if ($this->getLangs()){
            $this->initLang();
        }

        $elementModel->where($elementModel->getTableName() . '.' . $this->_moduleElement . '=?', $moduleElementId);
        if ($elementModel->colExists('ordem')){
            $elementModel->order('ordem');
        }        $rowset = $elementModel->fetchAll();
        if (!$rowset) {
            return $this;
        }
        $i = 1;
        foreach ($rowset as $row) {
            $params = array();
            $nome = 'element_' . $row->id;
            $params['label'] = $row->label;
            if ($row->required > 0) {
                $params['notnull'] = true;
            }
            if ($row->element == 'text') {
                if ($row->size > 0) {
                    $params['maxlength'] = $row->size;
                }
                $this->{$nome} = $this->Char($params);
            } elseif ($row->element == 'textarea') {
                $this->{$nome} = $this->Text($params);
            } elseif ($row->element == 'file') {
                $moduleConfig = new Goweb_Config(Goweb_Config_Ini::load(APPLICATION_PATH . '/' . $this->_moduleDir . '/config.ini', 'base'));
                if ($moduleConfig->files->target){
                    $params['target'] = $moduleConfig->files->target;
                }
                if ($moduleConfig->files->prefix){
                    $params['prefix'] = $moduleConfig->files->prefix;
                }
                if ($moduleConfig->files->max_size) {
                    $params['max_size'] = $moduleConfig->files->max_size;
                }
                $this->{$nome} = $this->File($params);
            } elseif ($row->element == 'image') {
                $moduleConfig = new Goweb_Config(Goweb_Config_Ini::load(APPLICATION_PATH . '/' . $this->_moduleDir . '/config.ini', 'base'));
                if ($moduleConfig->images->original->max_width && $moduleConfig->images->original->max_width){
                    $params['max_width'] = $moduleConfig->images->original->max_width;
                    $params['max_height'] = $moduleConfig->images->original->max_height;
                }
                if ($moduleConfig->images->target){
                    $params['target'] = $moduleConfig->images->target;
                }
                $params['sizes'] = $moduleConfig->images->sizes ? $moduleConfig->images->sizes : 'small,medium,big';
                foreach (explode(',', $params['sizes']) as $size){
                    if (!$moduleConfig->images->{$size}->width) continue;
                    foreach (array('width', 'height') as $type){
                        $params[$size . '_max_' . $type] = $moduleConfig->images->{$size}->{$type};
                    }
                    foreach (array('watermark', 'type_resize') as $type){
                        $params[$size . '_' . $type] = $moduleConfig->images->{$size}->{$type};
                    }
                }

                if ($moduleConfig->images->prefix){
                    $params['prefix'] = $moduleConfig->images->prefix;
                }

                if ($moduleConfig->images->max_size) {
                    $params['max_size'] = $moduleConfig->images->original->max_size;
                }
                $this->{$nome} = $this->Image($params);
            } else {
                // no caso de ser checkbox, radio ou select é guardado apenas o valor
                $params['maxlength'] = '200';
                $this->{$nome} = $this->Char($params);
            }
            $i++;
            if ($limite > 0 && $i >= $limite) {
                break;
            }
        }
        return $this;
    }
}