<?php

/**
 * Copyright (c) 2006-2022 LogicalDOC
 * WebSites: www.logicaldoc.com
 * 
 * No bytes were intentionally harmed during the development of this application.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
// no direct access
defined('_JEXEC') or die;

use logicaldoc\LDOCWebServicesFactory;
/*
use logicaldoc\bean\QueryParams;
use logicaldoc\bean\ResultSet;
use logicaldoc\bean\Document;
use logicaldoc\bean\Folder;
use logicaldoc\bean\FormElementComplex;
use logicaldoc\bean\QueryResult;
use logicaldoc\bean\Version;
use logicaldoc\bean\form\Input;
use logicaldoc\bean\form\Select;
use logicaldoc\bean\form\TextArea;
use logicaldoc\bean\form\CheckBox;
*/

jimport('joomla.application.component.controller');

class LogicalDOCControllerSearch extends JControllerLegacy {

    private $ws;
    private $rowConfiguration;
    private $rowsMetadata;

    public function display($cachable = false, $urlparams = false) {
        parent::display($cachable, $urlparams);
    }

    public function searchAdvanced() {
        JRequest::setVar('view', 'search');
        JRequest::setVar('layout', 'result');
        JRequest::setVar('content', JRequest::getVar('content'));
        JRequest::setVar('name', JRequest::getVar('name'));
        JRequest::setVar('keyword', JRequest::getVar('keyword'));
        JRequest::setVar('document', JRequest::getVar('document'));
        JRequest::setVar('folder', JRequest::getVar('folder'));
        JRequest::setVar('mimeType', JRequest::getVar('mimeType'));
        $this->display();
    }

    public function returnDesktop() {
        JRequest::setVar('view', 'desktop');
        JRequest::setVar('layout', 'view');
        $enter = 1;
        JRequest::setVar('enter', $enter);
        $this->display();
    }

    public function pagination() {
        require_once (JPATH_COMPONENT . DS . 'tables' . DS . 'configuration.php');
        $this->rowConfiguration = JTable::getInstance('Configuration', 'Table');
        $id = JRequest::getVar('id');
        $this->rowConfiguration->load($id);
        //Metadata
        require_once (JPATH_COMPONENT . DS . 'models' . DS . 'metadata.php');
        $modelMetadata = new LogicalDOCModelMetadata();
        $this->rowsMetadata = $modelMetadata->getObjects($this->rowConfiguration->idConfiguration);
        $start = (int) JRequest::getVar('start');
        $length = (int) JRequest::getVar('length');
        try {
            $sessionSearch = JFactory::getSession();

            $this->ws = LDOCWebServicesFactory::build($this->rowConfiguration->url, $this->rowConfiguration->user, $this->rowConfiguration->password);

            $queryParams = new QueryParams();
            $queryParams->setPath($this->rowConfiguration->ldocPath);
            $queryParams->setContent($sessionSearch->get('content'));
            $queryParams->setName($sessionSearch->get('name'));
            $keywords = array();
            $keywords[] = $sessionSearch->get('keyword');
            $queryParams->setKeywords($keywords);
            $queryParams->setDomain($sessionSearch->get('document') + $sessionSearch->get('folder'));
            $queryParams->setMimeType($sessionSearch->get('mimeType'));
            $results = $this->ws->findPaginated($queryParams, $start, $length);
            $resultServer = array(
                "draw" => (int) JRequest::getVar('draw'),
                "recordsTotal" => $results->getTotal(),
                "recordsFiltered" => $results->getTotal(),
                "data" => $this->output($results)
            );
            echo json_encode($resultServer);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    public function output(ResultSet $results) {
        $data = array();
        $queryResult = new QueryResult();
        foreach ($results->getResults() as $queryResult) {
            $row = array();
            if ($queryResult->getDocument() != null) {
                $document = new Document();
                $document = $queryResult->getDocument();
                $row[] = '<img src=" ' . $this->rowConfiguration->url . '/mime/' . $document->getMimeType() . '" />';
                $name = '';
                $name .= '<a  href="index.php?option=com_logicaldoc&view=desktop&task=download&format=raw&uuid=' . $document->getUuid() . '&id=' . $this->rowConfiguration->idConfiguration . '" >';
                $name .= substr($document->getPath(), strrpos($document->getPath(), '/') + 1);
                $name .= '</a>';
                $row[] = $name;
                $row[] = $this->formatSize($document->getActualVersion()->getSize());
                $time = strtotime($document->getCreated());
                $row[] = date('d/m/Y h:i:s', $time);
                $row[] = $document->getAuthor();
                $row[] = $document->getActualVersion()->getName();
                if (!empty($this->rowsMetadata)) {
                    $property = explode(".", $this->rowsMetadata[0]->property);
                    $group = str_replace("okp", "okg", $property[0]);
                    $formElements = $this->ws->getPropertyGroupProperties($document->getUuid(), $group);
                    $metadata = '';
                    foreach ($this->rowsMetadata as $rowMetadata) {
                        $metadata = '';
                        $metadata .= '<td style="white-space: nowrap;">';
                        foreach ($formElements as $formElement) {
                            if ($formElement instanceof Input) {
                                $name = $formElement->getName();
                                $value = $formElement->getValue();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= $value;
                                }
                            } else if ($formElement instanceof Select) {
                                $name = $formElement->getName();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= optionLabel($formElement->getOptions());
                                }
                            } else if ($formElement instanceof TextArea) {
                                $name = $formElement->getName();
                                $value = $formElement->getValue();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= $value;
                                }
                            } else if ($formElement instanceof CheckBox) {
                                $name = $formElement->getName();
                                $value = $formElement->isValue();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= $value;
                                }
                            }
                        }
                        $metadata .= '</td>';
                        $row[] = $metadata;
                    }
                }
            } if ($queryResult->getFolder() != null) {
                $folder = new Folder();
                $folder = $queryResult->getFolder();
                $mimeType = '';
                if ($folder->isHasChildren() == 'false') {
                    $mimeType = '<img src="' . JURI::base(true) . '/components/com_logicaldoc/assets/images/menuitem_childs.png" />';
                } else {
                    $mimeType = '<img src="' . JURI::base(true) . '/components/com_logicaldoc/assets/images/menuitem_empty.png" />  ';
                }
                $row[] = $mimeType;
                $name = '';
                $name .= '<a href="index.php?option=com_logicaldoc&view=desktop&layout=view&enter=1&uuid=' . $folder->getUuid() . '" >';
                $name .= substr($folder->getPath(), strrpos($folder->getPath(), '/') + 1);
                $name .= '</a>';
                $row[] = $name;
                $row[] = '';
                $time = strtotime($folder->getCreated());
                $row[] = date('d/m/Y h:i:s', $time);
                $row[] = $folder->getAuthor();
                $row[] = '';
                if (!empty($this->rowsMetadata)) {
                    $property = explode(".", $this->rowsMetadata[0]->property);
                    $group = str_replace("okp", "okg", $property[0]);
                    $formElements = $this->ws->getPropertyGroupProperties($folder->getUuid(), $group);
                    $metadata = '';
                    foreach ($this->rowsMetadata as $rowMetadata) {
                        $metadata = '';
                        $metadata .= '<td style="white-space: nowrap;">';
                        foreach ($formElements as $formElement) {
                            if ($formElement instanceof Input) {
                                $name = $formElement->getName();
                                $value = $formElement->getValue();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= $value;
                                }
                            } else if ($formElement instanceof Select) {
                                $name = $formElement->getName();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= optionLabel($formElement->getOptions());
                                }
                            } else if ($formElement instanceof TextArea) {
                                $name = $formElement->getName();
                                $value = $formElement->getValue();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= $value;
                                }
                            } else if ($formElement instanceof CheckBox) {
                                $name = $formElement->getName();
                                $value = $formElement->isValue();
                                if ($rowMetadata->property == $name) {
                                    $metadata .= $value;
                                }
                            }
                        }
                        $metadata .= '</td>';
                        $row[] = $metadata;
                    }
                }
            }
            $data[] = $row;
        }
        return $data;
    }

    public function redondear($numero, $decimales) {
        $factor = pow(10, $decimales);
        return (round($numero * $factor) / $factor);
    }

    public function formatSize($size) {
        $srt = "BIG";
        if ($size / 1024 < 1) {
            $srt = $size . " Bytes";
        } else if ($size / 1048576 < 1) {
            $srt = $this->redondear(($size / 1024), 1) . " KB";
        } else if ($size / 1073741824 < 1) {
            $srt = $this->redondear(($size / 1048576), 1) . " MB";
        } else if ($size / 1099511627776 < 1) {
            $srt = $this->redondear(($size / 1073741824), 1) . " GB";
        }
        return $srt;
    }

    public function optionLabel($options) {
        foreach ($options as $option) {
            if ($option->isSelected() == 'true') {
                return $option->getLabel();
            }
        }
    }

    public function optionValue($options) {
        foreach ($options as $option) {
            if ($option->isSelected() == 'true') {
                return $option->getValue();
            }
        }
    }

}

?>
