<?php

include("GnutecaWebServices.class.php");
class gnuteca3WebServicesSearchChildren
{
    private $webService;
    private $MIOLO;
    
    public function __construct() 
    {
        $this->webService = new GWebServices();
        $this->MIOLO = MIOLO::getInstance();
    }
    
    /**
     * Webservice para buscar os fascículos e artigos do material
     * @param int $clientId
     * @param string $clientPassword
     * @param int $controlNumber
     */
    public function getChildrenFields($clientId, $clientPassword, $controlNumber)
    {
        $retorno = new stdClass();

        // Define acesso ao método e define a classe do Webservice
        $this->webService->__setClient($clientId, $clientPassword);
        $this->webService->setClassName(get_class($this));

        // Verifica se o usuário possui acesso ao WebService
        if (!$this->webService->__checkMethod("getChildrenFields", false))
        {
            $retorno->message = $this->webService->__getErrorStr();
            return json_encode($retorno);
        }
        
        $busMaterialControl = $this->MIOLO->getBusiness('gnuteca3', 'BusMaterialControl');

        $materialType = $busMaterialControl->getTypeOfMaterial($controlNumber);
        $validMaterialTypes = [
            BusinessGnuteca3BusMaterialControl::TYPE_BOOK,
            BusinessGnuteca3BusMaterialControl::TYPE_COLLECTION,
            BusinessGnuteca3BusMaterialControl::TYPE_COLLECTION_FASCICLE,
            BusinessGnuteca3BusMaterialControl::TYPE_OTHER
        ];

        // Só pode ter filhos caso seja livro, coleção ou fascículo da coleção
        if (in_array($materialType, $validMaterialTypes)) 
        {
            $isCollection = $materialType == BusinessGnuteca3BusMaterialControl::TYPE_COLLECTION;
            $isCollectionFascicle = $materialType == BusinessGnuteca3BusMaterialControl::TYPE_COLLECTION_FASCICLE;

            // Define o formato de pesquisa de acordo com o tipo de material
            $busSearchFormat = $this->MIOLO->getBusiness('gnuteca3', 'BusSearchFormat');
            $searchFormat = $isCollection || $isCollectionFascicle ? SIMPLE_SEARCH_SEARCH_FORMAT_ID_DETAIL_FASCICLE : SIMPLE_SEARCH_SEARCH_FORMAT_ID_DETAIL_ARTICLE;

            // Seleciona os filhos de acordo com a unidade selecionada
            $libraryUnitId = $isCollectionFascicle ? null : MIOLO::_REQUEST('libraryUnitId');
        
            $childrens = $busMaterialControl->getChildren($controlNumber, $libraryUnitId);

            if ($isCollection)
            {
                $childrens = $this->sortChildrenByDateAndNumber($childrens, $searchFormat, $busSearchFormat);
            }
            
            if($childrens)
            {
                $stringData = $this->formatChildrenData($childrens, $searchFormat, $busSearchFormat);
                $retorno->materialChildren = $stringData;
            }
                        
            return json_encode($retorno);
        }
    
        $retorno->message = "Nenhum fascículo foi encontrado para o material";
        return json_encode($retorno);
    }
    
    private function formatChildrenData($childrens, $searchFormat, $busSearchFormat)
    {
        $data = array();
        
        foreach ($childrens as $line => $children)
        {
            $formatedString = $busSearchFormat->getFormatedString($children, $searchFormat, 'detail');
            $data[$line]['controlNumber'] = $children;
            $data[$line]['searchFormat'] = $formatedString;
        }
        $data = array_reverse($data);
        return $data;
    }
    
    // A lógica deste método foi copiada de GMaterialDetail->getChildrenFields
    private function sortChildrenByDateAndNumber($childrens, $searchFormat, $busSearchFormat)
    {
        $meses = array('jan' => 1, 'fev' => 2, 'mar' => 3, 'abr' => 4, 'maio' => 5, 'jun' => 6, 'jul' => 7, 'ago' => 8, 'set' => 9, 'out' => 10, 'nov' => 11, 'dez' => 12);
        
        $_childrens = array();
        $_fim = array();
        $count = array();
        
        $busMaterial = $this->MIOLO->getBusiness('gnuteca3', 'BusMaterial');
        
        foreach ( $childrens as $child )
        {
            $ano = substr($busMaterial->getContent($child, '949', '4'), 0, 4);
            if ( !$ano || strlen($ano) == 0 )
            {
                $_info = $busSearchFormat->getFormatedString($child, $searchFormat, 'detail');
                
                preg_match('/[1-9][0-9][0-9][0-9]./', $_info, $matches, PREG_OFFSET_CAPTURE);
                $ano = trim($matches[0][0], '.');
                
                if ( strlen($ano) == 0 )
                {                    
                    preg_match('/[1-9][0-9][0-9][0-9]/', $_info, $matches, PREG_OFFSET_CAPTURE);
                    $ano = trim($matches[0][0], '.');
                    
                    // Obtém o mês do fascículo.
                    $parts = explode(',', $_info);
                    $parts = explode(' ', trim(end($parts)));
                    $mes = strtolower(str_replace('.', '', $parts[0]));
                    if ( !$meses[$mes] )
                    {
                        $mes = substr($mes, 0, strpos($mes, '/'));
                        $mes = $meses[$mes];
                    }
                    else
                    {
                        $mes = $meses[$mes];
                    }
                }
                
                if ( strlen($ano) > 4 )
                {
                   
                    preg_match('/[1-9][0-9][0-9][0-9]/', $ano, $matches, PREG_OFFSET_CAPTURE);
                    $ano = trim($matches[0][0], '.');
                }
            }
            
            $_info = $busSearchFormat->getFormatedString($child, $searchFormat, 'detail');
            preg_match("/no?\. [0-9]{1,4}?[\-\/0-9]{0,4}?[ \w\W]{0,100}\,/", $_info, $matches, PREG_OFFSET_CAPTURE);
            $_lastN = $_n;

            if ( strlen($matches[0][0]) > 0 )
            {
                $_n = trim(str_replace('n.', '', $matches[0][0]), ' ,.-_;');
                if ( substr_count($_n, '-') > 0 )
                {
                    $_n = explode('-', $_n);
                    $_n = $_n[0] . '.' . $_n[1];
                }
                
                if ( !is_numeric($_n) )
                {
                    
                    $_n = preg_match('/[0-9][0-9]/', $_n, $matches, PREG_OFFSET_CAPTURE);
                    if ( is_numeric($matches[0][0]) )
                    {
                        $_n = $matches[0][0];
                    }
                    else
                    {
                        $_n = $_lastN + 1;
                    }
                }
            }
            else
            {
                $_n = 0;
            }
            
            if ( !$count[$ano] )
            {
                $count[$ano] = 10;
            }
            
            $_v = substr_count($_info, 'v.');
            if ( !$_n && count($matches) == 0 && $_v == 0 )
            {
                $_fim[] = $child;
                continue;
            }

            if ( $_n > 0 )
            {
                $_childrens[$ano][$mes][$_n][] = $child;
                $count[$ano] = $_n + 1;
            }
            else
            {
                $_childrens[$ano][$mes][-$count[$ano]][] = $child;
                $count[$ano]++;
            }
        }
        
        $childrens = array();
        $i = 0;
        ksort($_childrens);
        foreach ( $_childrens as $ano => $_child )
        {
            ksort($_childrens[$ano]);
            foreach ( $_child as $mes => $_ch )
            {
                ksort($_childrens[$ano][$mes]);
                foreach ( $_ch as $num => $c )
                {
                    ksort($_childrens[$ano][$mes][$num]);
                }
            }
        }
        
        if ( count($_fim) > 0 )
        {
            
            foreach ( $_fim as $fim )
            {
                $childrens[$i] = $fim;
                $i++;
            }
        }
        
        foreach ( $_childrens as $ano => $_child )
        {
            foreach ( $_child as $_c )
            {
                foreach ( $_c as $_ch )
                {
                    foreach ( $_ch as $_cnumber )
                    {
                        $childrens[$i] = $_cnumber;
                        $i++;
                    }
                }
            }
        }
        
        return $childrens;
    }
}