<?php
/**
 * <--- Copyright 2005-2011 de Solis - Cooperativa de Soluções Livres Ltda. e
 * Univates - Centro Universitário.
 * 
 * Este arquivo é parte do programa Gnuteca.
 * 
 * O Gnuteca é um software livre; você pode redistribuí-lo e/ou modificá-lo
 * dentro dos termos da Licença Pública Geral GNU como publicada pela Fundação
 * do Software Livre (FSF); na versão 2 da Licença.
 * 
 * Este programa é distribuído na esperança que possa ser útil, mas SEM
 * NENHUMA GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO
 * ou APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/GPL em
 * português para maiores detalhes.
 * 
 * Você deve ter recebido uma cópia da Licença Pública Geral GNU, sob o título
 * "LICENCA.txt", junto com este programa, se não, acesse o Portal do Software
 * Público Brasileiro no endereço www.softwarepublico.gov.br ou escreva para a
 * Fundação do Software Livre (FSF) Inc., 51 Franklin St, Fifth Floor, Boston,
 * MA 02110-1301, USA --->
 * 
 * Bar code form
 *
 * @author Moises Heberle [moises@solis.coop.br]
 *
 * @version $Id$
 *
 * \b Maintainers \n
 * Eduardo Bonfandini [eduardo@solis.coop.br]
 * Jamiel Spezia [jamiel@solis.coop.br]
 * Luiz Gregory Filho [luiz@solis.coop.br]
 * Moises Heberle [moises@solis.coop.br]
 * Sandro R. Weisheimer [sandrow@solis.coop.br]
 *
 * @since
 * Class created on 25/09/2008
 *
 **/


/**
 * Form to manipulate a preference
 **/
class FrmBarCode extends GForm
{
    public $MIOLO;
    public $module;
    public $action;
    public $function;
    public $busLibraryUnit;

    const INTERVAL_CONTINUOUS = 1;
    const INTERVAL_DISCRETE   = 2;
    const SIZE_SMALL          = '1';
    const SIZE_MEDIUM         = '1.5';
    const SIZE_BIG            = '2';
    const TYPE_CODABAR        = 'codabar';
    const TYPE_BARCODE128     = 'barcode128';

    /**
     * Class constructor
     **/
    function __construct()
    {
    	//Define os tipos de codigo de barra.
    	//Os valores devem bater com o nome das classes de geração das barras

        $this->MIOLO    = MIOLO::getInstance();
        $this->module   = MIOLO::getCurrentModule();
        $this->action   = MIOLO::getCurrentAction();
        $this->function = MIOLO::_REQUEST('function');
        $this->busLibraryUnit = $this->MIOLO->getBusiness($this->module, 'BusLibraryUnit');

        $this->forceCreateFields = true;
        $this->setTransaction('gtcBarcode');
        parent::__construct(_M('Código de barras', $this->module), $this->action);
        $this->setHelp(get_class($this), $this->module, $this->action);
        $this->setIcon(GUtil::getImageTheme('barcode-16x16.png'));

       	if (GForm::primeiroAcessoAoForm())
       	{
       		GRepetitiveField::clearData('codes');
       	}
    }


    /**
     * Default method to define fields
     **/
    public function mainFields()
    {
        $options = array(
            array(_M('Contínuo', $this->module), self::INTERVAL_CONTINUOUS),
            array(_M('Discreto', $this->module), self::INTERVAL_DISCRETE),
        );

        $lbl = new MLabel( _M('Intervalo', $this->module) . ':' );
        $lbl->setWidth(FIELD_LABEL_SIZE);
        $interval = new MRadioButtonGroup('interval', null, $options, self::INTERVAL_CONTINUOUS, null, 'vertical');
        $form     = $this->manager->page->getFormId();
        $interval->addAttribute('onchange', "miolo.doAjax( (dojo.byId('interval_0').checked ? 'getContinuousFields' : 'getDiscreteFields') ,'','{$form}');");
        $fields[] = new GContainer('hctInterval', array($lbl, $interval));

        $fields[] = new MDiv('divInterval', $this->getContinuousFields(TRUE));

        //relação de tamanhos de fontes
        for ($i = 1 ; $i <= 30 ; $i++)
        {
            $sizeList[] = array($i,$i);
        }

        $fields[] = $fontSize = new GSelection('fontSize', '10', _M('Tamanho da fonte', $this->module) , $sizeList , false, null, null, true);
        $fontSize->addStyle('width','60px');

        $fields[] = new MTextField('beginLabel', '1', _M('Etiqueta inicial', $this->module), 5);
        $fields[] = new MTextField('text', null, _M('Texto', $this->module), FIELD_DESCRIPTION_SIZE, _M( 'Pode-se utilizar campos marc e funções. Ex.: $245.a.','gnuteca3') );

        //Tamanho das barras
        $opts = array(
            array(_M('Pequeno', $this->module),  self::SIZE_SMALL),
            array(_M('Médio', $this->module), self::SIZE_MEDIUM),
            array(_M('Maior', $this->module), self::SIZE_BIG)
        );
        $lbl = new MLabel( _M('Tamanho do código de barras', $this->module) . ':' );
        $lbl->setWidth(FIELD_LABEL_SIZE);
        $size = new MRadioButtonGroup('size', null, $opts, self::SIZE_SMALL, null, 'vertical');
        $fields[] = new GContainer('hctSize', array($lbl, $size));

        //Tipo de barra
        $opts = array(
            array(_M('Codabar', $this->module),     self::TYPE_CODABAR),
            array(_M('Código de barras 128', $this->module), self::TYPE_BARCODE128),
        );
        $lbl = new MLabel( _M('Tipo', $this->module) . ':' );
        $lbl->setWidth(FIELD_LABEL_SIZE);
        $type = new MRadioButtonGroup('type', null, $opts, self::TYPE_CODABAR, null, 'vertical');
        $fields[] = new GContainer('hctType', array($lbl, $type));

        $characters[] = array('0', 'Não fixos');
        $characters[] = array('6', '6');
        $characters[] = array('8', '8');
        $characters[] = array('10', '10');
        $characters[] = array('12', '12');
        $fields[] = $characters = new GSelection('characters', $this->getFormValue('characters', '8'), _M('Caracteres', $this->module), $characters);
        $characters->addStyle('width','80px');

        $labelLayout = new MLabel (_M('Código do modelo da etiqueta:', $this->module));
        $labelLayout->setWidth(FIELD_LABEL_SIZE);
        $labelLayoutId = new GLookupTextField ('labelLayout',  DEFAULT_BARCODE_LABEL_LAYOUT, '', FIELD_LOOKUPFIELD_SIZE, null, null, 'labelLayoutDescription, lines, columns, topMargin, leftMargin, verticalSpacing, horizontalSpacing, labelHeight, labelWidth, pageFormat', $this->module, 'LabelLayout');
        $labelLayoutId->setContext($this->module, $this->module, 'LabelLayout', 'filler', 'labelLayout,labelLayoutDescription,lines,columns,topMargin,leftMargin,verticalSpacing,horizontalSpacing,labelHeight,labelWidth,pageFormat', '', true);
        $labelLayoutDescription = new MTextField ('labelLayoutDescription', '', null, FIELD_DESCRIPTION_LOOKUP_SIZE);
        $labelLayoutDescription->setReadOnly(true);
        $labelLayoutContainer = new GContainer('labelLayoutContainer', array ($labelLayout, $labelLayoutId, $labelLayoutDescription));
        $fieldsG[] = $labelLayoutContainer;
       
        $linesL = new MLabel (_M('Linhas', $this->module));
        $linesL->setWidth(FIELD_LABEL_SIZE);
        $linesF = new MTextField('lines', null, null, 8);
        $fieldsG[] = new GContainer('linesG', array($linesL, $linesF));

        $columnsL = new MLabel (_M('Colunas', $this->module));
        $columnsL->setWidth(FIELD_LABEL_SIZE);
        $columnsF = new MTextField('columns', null, null, 8);
        $fieldsG[] = new GContainer('columnsG', array($columnsL, $columnsF));

        $topMarginL = new MLabel (_M('Margem superior', $this->module));
        $topMarginL->setWidth(FIELD_LABEL_SIZE);
        $topMarginF = new MTextField('topMargin', null, null, 8);
        $fieldsG[] = new GContainer('topMarginG', array($topMarginL, $topMarginF));

        $leftMarginL = new MLabel (_M('Margem esquerda', $this->module));
        $leftMarginL->setWidth(FIELD_LABEL_SIZE);
        $leftMarginF = new MTextField('leftMargin', null, null, 8);
        $fieldsG[] = new GContainer('leftMarginG', array($leftMarginL, $leftMarginF));

        $verticalSpacingL = new MLabel (_M('Espaco Vertical', $this->module));
        $verticalSpacingL->setWidth(FIELD_LABEL_SIZE);
        $verticalSpacingF = new MTextField('verticalSpacing', null, null, 8);
        $fieldsG[] = new GContainer('verticalSpacingG', array($verticalSpacingL, $verticalSpacingF));

        $horizontalSpacingL = new MLabel (_M('Espaço horizontal', $this->module));
        $horizontalSpacingL->setWidth(FIELD_LABEL_SIZE);
        $horizontalSpacingF = new MTextField('horizontalSpacing', null, null, 8);
        $fieldsG[] = new GContainer('horizontalSpacingG', array($horizontalSpacingL, $horizontalSpacingF));

        $labelHeightL = new MLabel (_M('Altura', $this->module));
        $labelHeightL->setWidth(FIELD_LABEL_SIZE);
        $labelHeightF = new MTextField('labelHeight', null, null, 8);
        $fieldsG[] = new GContainer('$labelHeightG', array($labelHeightL, $labelHeightF));

        $labelWidthL = new MLabel (_M('Largura', $this->module));
        $labelWidthL->setWidth(FIELD_LABEL_SIZE);
        $labelWidthF = new MTextField('labelWidth', null, null, 8);
        $fieldsG[] = new GContainer('labelWidthG', array($labelWidthL, $labelWidthF));

        $pageFormatL = new MLabel (_M('Formato da página', $this->module));
        $pageFormatL->setWidth(FIELD_LABEL_SIZE);
        $pageFormatF = new MTextField('pageFormat', null, null, 15);
        $fieldsG[] = new GContainer('pageFormatG', array($pageFormatL, $pageFormatF));

        $fields[] = new MBaseGroup('baseFields', _M('Configuração da página', $this->module), $fieldsG, 'vertical');

        $fields[] = new MButton('BtnPrint', _M('Gerar', $this->module) , GUtil::getAjax('tbBtnPrint_click'), GUtil::getImageTheme('print-16x16.png'));

        $fields[] = new MSeparator('');

        $this->forceFormContent = TRUE;
        $this->setFields($fields);
        $this->setLabelWidth(FIELD_LABEL_SIZE);
        $this->setShowPostButton(false);

        
        $this->_toolBar->disableButton( MToolBar::BUTTON_DELETE );
        $this->_toolBar->disableButton( MToolBar::BUTTON_NEW );
        $this->_toolBar->disableButton( MToolBar::BUTTON_RESET );
        $this->_toolBar->disableButton( MToolBar::BUTTON_SAVE );
        
        if ( $this->primeiroAcessoAoForm()  && ( $this->GetField('interval')->value == self::INTERVAL_DISCRETE ) ) 
        {
            $this->page->onload(  GUtil::getAjax('getDiscreteFields') );
        }
    }


    /**
     * Obtem os fields para modo contínuo
     *
     * @param unknown_type $return
     * @return unknown
     */
    public function getContinuousFields($return = FALSE)
    {
    	$lbl = new MLabel( _M('Código inicial', $this->module) );
    	$lbl->setWidth(FIELD_LABEL_SIZE);
    	$flds[] = $lbl;
        $flds[] = new MTextField('beginCode', null, null, FIELD_ID_SIZE);

        $flds[] = new MSeparator();
        $lbl = new MLabel( _M('Código final', $this->module) );
        $lbl->setWidth(FIELD_LABEL_SIZE);
        $flds[] = $lbl;
        $flds[] = new MTextField('endCode', null, null, FIELD_ID_SIZE);

        $hct = new MDiv('hctContinuous', $flds);
        if ($return)
        {
        	return $hct;
        }
        $this->setResponse($hct, 'divInterval');
        $this->setFocus('beginCode');
    }


    /**
     * Obtem os fields para modo discreto
     *
     */
    public function getDiscreteFields()
    {
        $flds[] = new MTextField('itemNumber', null, _M('Número do exemplar', $this->module), FIELD_ID_SIZE);
        $cols[] = new MGridColumn(_M('Número do exemplar', $this->module), MGrid::ALIGN_LEFT, true, null, true, 'itemNumber');
        $valids[] = new GnutecaUniqueValidator('itemNumber', _M('Número do exemplar', $this->module), 'required');
        $interval = new GRepetitiveField('codes', _M('Itens', $this->module), $cols, $flds);
        $interval->setValidators($valids);
        $fields[] = $interval;
        $this->setResponse($fields, 'divInterval');
        $this->setFocus('itemNumber');
    }


    /**
     * Event triggered when user chooses Print on toolbar
     **/
    public function tbBtnPrint_click($sender=NULL)
    {
        $labelLayout->lines              = $this->getFormValue('lines');
        $labelLayout->columns            = $this->getFormValue('columns');
        $labelLayout->topMargin          = $this->getFormValue('topMargin');
        $labelLayout->leftMargin         = $this->getFormValue('leftMargin');
        $labelLayout->verticalSpacing    = $this->getFormValue('verticalSpacing');
        $labelLayout->horizontalSpacing  = $this->getFormValue('horizontalSpacing');
        $labelLayout->labelHeight        = $this->getFormValue('labelHeight');
        $labelLayout->labelWidth         = $this->getFormValue('labelWidth');
        $labelLayout->pageFormat         = $this->getFormValue('pageFormat');

        $data->fontSize   = $this->getFormValue('fontSize');
        $data->beginLabel = $this->getFormValue('beginLabel');
        $data->characters = $this->getFormValue('characters');
        $data->text       = $this->getFormValue('text');
        $data->size       = $this->getFormValue('size');
        $data->type       = $this->getFormValue('type');

        if ($this->getFormValue('interval') == self::INTERVAL_CONTINUOUS)
        {
            $beginCode   = $this->beginCode->value;
            $endCode     = $this->endCode->value;
            $lengthfirst = strlen($beginCode);
            for ($x=$beginCode; $x<=$endCode; $x++)
            {
                $codes[] = GUtil::strPad($x, $data->characters, '0', STR_PAD_LEFT);
            }
        }
        else //self::INTERVAL_DISCRETE
        {
            $_codes = GRepetitiveField::getData('codes');
            $codes  = null;
            if ($_codes)
            {
                foreach ($_codes as $code)
                {
                    //Não adicionar exemplares excluídos
                    if (!$code->removeData)
                    {
                        if ($code->itemNumber)
                        {
                            $codes[] = GUtil::strPad($code->itemNumber, $data->characters, '0', STR_PAD_LEFT);
                        }
                    }
                }
            }
        }

        $this->MIOLO->getClass($this->module, 'GPDFLabel');
        $this->MIOLO->getClass($this->module, 'report/rptBarCode');
        $report = new rptBarCode($labelLayout, $data, $codes);
        $report->showDownloadInfo();
    }
}
?>