<?php
/**
 * FrmZ3950 form
 *
 * @author Sandro Roberto Weisheimer [sandrow@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/05/2009
 *
 * \b Organization: \n
 * SOLIS - Cooperativa de Solucoes Livres \n
 * The Gnuteca3 Development Team
 *
 * \b CopyLeft: \n
 * CopyLeft (L) 2008 SOLIS - Cooperativa de Solucoes Livres \n
 *
 * \b License: \n
 * Licensed under GPL (for further details read the COPYING file or http://www.gnu.org/copyleft/gpl.html )
 *
 * \b History: \n
 * See history in SVN repository: http://gnuteca.solis.coop.br
 */


/**
 * Form to manipulate a preference
 **/
class FrmZ3950Search extends GnutecaForm
{
	public $MIOLO;
	public $module;
    public $busZ3950Servers, $busPreCatalogue, $busSearchFormat;
    public $z3950;
    public $grid;
    public $format;

    public function __construct()
    {
    	$this->MIOLO   = MIOLO::getInstance();
    	$this->module  = MIOLO::getCurrentModule();

    	$this->MIOLO->getClass($this->module, 'GnutecaZ3950');
    	$this->MIOLO->getClass($this->module, 'GnutecaFunction');

    	$this->z3950 = new GnutecaZ3950();

        $this->busZ3950Servers  = $this->MIOLO->getBusiness($this->module, 'BusZ3950Servers');
        $this->busPreCatalogue  = $this->MIOLO->getBusiness($this->module, 'BusPreCatalogue');
        $this->busSearchFormat  = $this->MIOLO->getBusiness($this->module, 'BusSearchFormat');

        parent::__construct(TITLE_SEARCH);

        $this->setLabelWidth(FIELD_LABEL_SIZE);
		$this->defaultButton = false;
        $this->eventHandler();

        $this->getGrid();
        if ( $this->primeiroAcessoAoForm() && strlen(MIOLO::_REQUEST('event')) == 0 )
        {
            $this->setFocus('serverId');
        }
        if (MIOLO::_REQUEST('pn_page'))
        {
            $this->tbBtnSearch_click( (Object)$_REQUEST );
        }
    }


    /**
     * Cria os campos do formulario
     *
     */
    public function createFields()
    {
        $fields[] = new MDiv("divError");
        $fields[] = new GnutecaSelection('serverId', null, _M('Servers', $this->module), $this->busZ3950Servers->listZ3950Servers(), false, '', '', true);
        $fields[] = new MTextField('description', null, _M('Termo da pesquisa', $this->module), FIELD_DESCRIPTION_SIZE);

        $f = $this->z3950->getRelationOfMarc21AndZ3950();
        $ok = true;
        foreach ($f as $id => $label)
        {
            $lbl        = new MLabel("$label:");
            $lbl        ->setWidth(FIELD_LABEL_SIZE);
            $radF       = new MRadioButton('searchField', $id, null, $ok, null, MRadioButton::LAYOUT_HORIZONTAL);
            $radios[]   = new MHContainer(null, array($lbl, $radF));
            $ok = false;
        }


        $fields[] = new MVContainer(null, $radios);
        //$fields[] = new MCheckBox('accurateTerm', true, null, MUtil::getBooleanValue($formContent['accurateTerm'] ) , _M('Accurate term', $this->module) );

    	//$fields[]  = new MButton('myBtnSearch', _M('Search', $this->module), ':tbBtnSearch_click');
		$btnSearch = new MButton('btnSearch', '<b>'._M('Search', $this->module).'</b>', ':tbBtnSearch_click', $this->MIOLO->getUI()->getImage($this->module, 'search-16x16.png'));
		$btnSearch->addStyle('height','30px');
		$fields[]  = $btnSearch;
		$fields[]  = new MSeparator();

		//divSearch
		$divSearch  = new MDiv('divSearch');
		$divSearch  ->setInner($this->getGrid());
		$fields[]   = $divSearch;

		$fields[]   = new MDiv('divAux');
        $this->setFields($fields);

        $validators[] = new MRequiredValidator('description');
        $this->setValidators($validators);
    }


    /**
     * Enter description here...
     *
     * @param unknown_type $msg
     */
    function setError($msg)
    {
        $e = new MPrompt();
        $er = $e->Error($msg, '', _M("Errors", $this->module));
        $fields[] = new MDiv(null,  $er);
        $this->setResponse($fields, 'divError');
    }


    /**
     * Enter description here...
     *
     * @param unknown_type $args
     */
    public function tbBtnSearch_click($args)
    {
        $this->setResponse('', 'divError');
        if(!strlen($args->description))
        {
            $this->setError(_M("The field 'Description' is required!", $this->module));
            return false;
        }
        $this->setResponse('', 'divError');

        $server = $this->busZ3950Servers->getServer($args->serverId);

        clog("host: $server->host");

        if(!$this->z3950->connect($server->host))
        {
            $this->setError($this->z3950->getErrorStr());
            return false;
        }

        $this->z3950->setSintax($server->sintax);

        $this->z3950->addTagSearch(trim($args->searchField), trim($args->description));
        clog("$args->searchField, $args->description");


        $this->z3950->setRange(($args->pn_page ? $args->pn_page - 1 : 0), 50);

        $this->grid = $this->getGrid();

        clog($this->z3950->mountQuery());

        if(!$this->z3950->search())
        {
            if(strlen($this->z3950->getErrorStr()))
            {
                $this->setError($this->z3950->getErrorStr());
            }
            else
            {
                $this->grid->setData(array());
                $this->setResponse( $this->grid , 'divSearch');
            }
            return false;
        }

        $this->z3950->setTimeOut();
        clog("Total Hist: ". $this->z3950->getHits() . " ");

        if(!$return = $this->z3950->getRecord(null,null, $server->recordType))
        {
            if(strlen($this->z3950->getErrorStr()))
            {
                $this->setError($this->z3950->getErrorStr());
            }
            else
            {
                $this->grid->setData(array());
                $this->setResponse( $this->grid , 'divSearch');
            }
            return false;
        }

        $return = $this->z3950->makeResult($return, $server->recordType);

        $data = array();
        $_SESSION['z3950'] = null;
        foreach ($return as $line => $content)
        {
            $data[$line] = array('', serialize($content), $line);
            $_SESSION['z3950'][$line] = serialize($content);
        }

        $this->grid->setData($data);

        $this->setResponse($this->grid, 'divSearch');
    }


    /**
     * Retorna a grid
     *
     * @return unknown
     */
    public function getGrid()
    {
        $this->grid = $this->MIOLO->getUI()->getGrid($this->module, "GrdZ3950Search");
        $this->grid->emptyMsg = '';
        $this->grid->setCSV(FALSE);

        return $this->grid;
    }


    public function detail( $args )
    {
        $this->format   = $this->busSearchFormat->getSearchFormat(Z3950_SEARCH_FORMAT_ID);
        $content               = unserialize($_SESSION['z3950'][$args]);
        $gnutecaFunction = new GnutecaFunction();

        foreach ($content as $tag => $registros)
        {
            $subfields = $registros->subfields;
            foreach ($subfields as $subf => $subContent)
            {
                $contentFormated = "";
                foreach ($subContent as $lineSub => $cont)
                {
                    if(strlen($contentFormated))
                    {
                        $contentFormated.= "\n";
                    }
                    $contentFormated.= "$cont->content";
                }

                $gnutecaFunction->setVariable("\${$tag}.{$subf}", $contentFormated);
            }
        }

        $formatDetail = str_replace("\n", '', $this->format->searchPresentationFormat[0]->detailFormat);
        $gnutecaFunction->setVariable('$LN', "\n");
        $content = $gnutecaFunction->interpret($formatDetail, true);
        $content = str_replace("\n", '<br>', $content);
        $content = preg_split('/<([ \/]{0,}?[bB][rR][ \/]{0,}?)>/U', $content);

        // converte para o formato da MTableRaw
        if ( is_array( $content ) )
        {
            $detailData = null;
            foreach ($content as $line => $info)
            {
                $detailData[$line] = array( strlen($info) ? $info : '--');
            }

            $tableDetail = new MTableRaw( null, $detailData , array( _M('Material Detail', $module) ), null);
            $tableDetail->setAlternate(true);
            $tableDetail->addAttribute('width',     '99%');
            $tableDetail->addAttribute('height',    '300px');
            $tableDetail->addAttribute('overflow',  'auto');

            $div = new MDiv('', $tableDetail);
            $div->addBoxStyle('width',     '99%');
            $div->addBoxStyle('height',    '300px');
            $div->addBoxStyle('overflow',  'auto');

            $this->injectContent($div, true, true);
            return;
        }

        $this->injectContent(new MDiv('', $content), true, true);
        return null;
    }


    /* import um determinado material */
    public function importMaterial($args)
    {
        $content    = unserialize($_SESSION['z3950'][$args]);
        $response   = '';

        if(is_array($content))
        {
            $controlNumber = $this->busPreCatalogue->getNextControlNumber();

            foreach ($content as $tag => $registros)
            {
                $subfields = $registros->subfields;
                foreach ($subfields as $subf => $subContent)
                {
                    foreach ($subContent as $lineSub => $cont)
                    {
                        $this->busPreCatalogue->clean();
                        $this->busPreCatalogue->controlNumber     = $controlNumber;
                        $this->busPreCatalogue->fieldid           = $tag;
                        $this->busPreCatalogue->subfieldid        = $subf;
                        $this->busPreCatalogue->line              = $lineSub;
                        $this->busPreCatalogue->indicator1        = null;
                        $this->busPreCatalogue->indicator2        = null;
                        $this->busPreCatalogue->content           = $cont->content;
                        $this->busPreCatalogue->searchContent     = $this->busPreCatalogue->prepareSearchContent("{$tag}.{$subf}", $cont->content);
                        $this->busPreCatalogue->insertMaterial();
                    }
                }
            }

            $response = _M("Registro inserido com sucesso na pré-catalogação. Seu número de controle da pré-catalogação é: $controlNumber", $this->module);
        }
        else
        {
            $response = _M("Não foi possível importar os dados para a pré-catalogação.", $this->module);
        }


        $this->injectContent(new MDiv('', $response), true, true);
    }
}
?>
