<?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 --->
 * 
 * FrmBackOfBook 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 Roberto Weisheimer [sandrow@solis.coop.br]
 *
 * @since
 * Class created on 05/11/2008
 *
 **/


/**
 * Form to manipulate back of book print
 **/
class FrmBackOfBook extends GForm
{
    public $MIOLO;
    public $module;
    public $business;
    public $busExemplaryControl;
    public $busLibraryUnit;

    const INTERVAL_CONTINUOUS   = 1;
    const INTERVAL_DISCRETE     = 2;
    const OPTION_CONTROL_NUMBER = 1;
    const OPTION_ITEM_NUMBER    = 2;

    public function __construct()
    {
        $this->MIOLO    = MIOLO::getInstance();
        $this->module   = MIOLO::getCurrentModule();
        $this->business            = $this->MIOLO->getBusiness($this->module, 'BusFormatBackOfBook');
        $this->busExemplaryControl = $this->MIOLO->getBusiness($this->module, 'BusExemplaryControl');
        $this->busLibraryUnit      = $this->MIOLO->getBusiness($this->module, 'BusLibraryUnit');

        //Define internal format options
        define('OPTION_ILABEL_NO',       1);
        define('OPTION_ILABEL_YES_SAME', 2);
        define('OPTION_ILABEL_YES_DIFF', 3);
        define('OPTION_ILABEL_ONLY',     4);

        $this->forceCreateFields = true;
        $this->setTransaction('gtcBackOfBook');
        parent::__construct( _M('Lombada', $this->module) );

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

        //força formulário de busca
        $this->setSearchFunction('test');
    }

    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));

        $options = array(
            array(_M('Número do exemplar', $this->module), self::OPTION_ITEM_NUMBER),
            array(_M('Número de controle', $this->module), self::OPTION_CONTROL_NUMBER),
        );
        $lbl = new MLabel( _M('Exemplares', $this->module) . ':' );
        $lbl->setWidth(FIELD_LABEL_SIZE);
        $exemplarys = new MRadioButtonGroup('exemplarys', null, $options, self::OPTION_ITEM_NUMBER, null, 'vertical');
        $fields[] = new GContainer('hctInterval', array($lbl, $exemplarys));


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

        $options = array(
            OPTION_ILABEL_NO       => _M('Não', $this->module),
            OPTION_ILABEL_YES_SAME => _M('Sim, na mesma etiqueta', $this->module),
            OPTION_ILABEL_YES_DIFF => _M('Sim, em etiqueta diferente', $this->module),
            OPTION_ILABEL_ONLY     => _M('Somente etiqueta interna', $this->module)
        );
        
        $fields[] = new GSelection('internalLabel', 1, _M('Etiqueta interna', $this->module), $options);
        $fields[] = new GSelection('formatBackOfBookId', 1, _M('Formato da lombada', $this->module), $this->business->listFormatBackOfBook());

        $fields[] = new MSeparator();

        //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 MIntegerField('beginLabel', '1', _M('Etiqueta inicial', $this->module), 5);

        $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'));

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

        //desabilita botões da toolbar
        $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($return = FALSE)
    {
        $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');
    }


    public function tbBtnPrint_click($data = null)
    {
        $beginCode     = $this->beginCode->value;
        $endCode       = $this->endCode->value;
        $interval      = $data->interval;
        $exemplarys    = $data->exemplarys;

        if ( ($interval == self::INTERVAL_CONTINUOUS) && ($exemplarys == self::OPTION_ITEM_NUMBER) )
        {
            $lengthFirst = strlen(trim($beginCode));

            for ($x=$beginCode; $x<=$endCode; $x++)
            {
                $itemNumber = GUtil::strPad($x, $lengthFirst, '0', STR_PAD_LEFT);
                $codes[$x] = $this->busExemplaryControl->getExemplaryControl( $itemNumber );
            }
        }

        if ( ($interval == self::INTERVAL_DISCRETE) && ($exemplarys == self::OPTION_ITEM_NUMBER) )
        {
            $codeList = GRepetitiveField::getData('codes');
            $codes    = null;

            if ($codeList)
            {
                foreach ($codeList as $key => $c)
                {
                    //Não adicionar exemplares excluídos
                    if (!$c->removeData)
                    {
                        $codes[$key] = $this->busExemplaryControl->getExemplaryControl($c->itemNumber);
                    }
                }
            }
        }

        if ( ($interval == self::INTERVAL_CONTINUOUS) && ($exemplarys == self::OPTION_CONTROL_NUMBER) )
        {
            $lengthFirst = strlen(trim($beginCode));

            for ($x=$beginCode; $x<=$endCode; $x++)
            {
                $itemNumber = GUtil::strPad($x, $lengthFirst, '0', STR_PAD_LEFT);
                $exemplary = $this->busExemplaryControl->getExemplaryOfMaterial($itemNumber);

                if ($exemplary)
                {
                    foreach ($exemplary as $ex)
                    {
                        $codes[ $ex->itemNumber ] = $ex;
                    }
                }
            }
        }

        if ( ($interval == self::INTERVAL_DISCRETE) && ($exemplarys == self::OPTION_CONTROL_NUMBER) )
        {
            $codeList = GRepetitiveField::getData('codes');
            $codes    = null;
            if ($codeList)
            {
                foreach ($codeList as $c)
                {
                    //Não adicionar números de controle excluídos
                    if (!$c->removeData)
                    {
                        $exemplary = $this->busExemplaryControl->getExemplaryOfMaterial($c->itemNumber);

                        if ($exemplary)
                        {
                            foreach ($exemplary as $ex)
                            {
                                $codes[ $ex->itemNumber ] = $ex;
                            }
                        }
                    }
                }
            }
        }

        $this->MIOLO->getClass($this->module, 'GPDFLabel');
        $this->MIOLO->getClass($this->module, 'report/rptBackOfBook');

        $report = new rptBackOfBook($data, $codes);
        $report->showDownloadInfo();
    }
}
?>
