<?php

class kohaBK implements sigb {
    
    const version = "1.0.0";
    const nameClass = "koha";
    
    public $hostData;

    static function version() {
        return self::version;
    }

    static function infos() {
        return self::nameClass;
    }

    static function fullInfos() {
        return 'SIGB : Koha<br />Agent SIGB : '.self::infos().' (version : '.self::version().')';
    }
    
    //Retourne les infos exemplaires
    public function copyDetails($noticeid, $institution, $userInt="") {
        $file = "exportISO/".$institution."/lock";
        if (file_exists($file)){
            $last_mod = filemtime($file);
            $time = time();
            $intervalle = $time - $last_mod;
            if ($intervalle >= 172800) @unlink($file); 
        }
        try {
            $result = @file_get_contents(rtrim($this->hostData, '/').'/cgi-bin/koha/webservice/rest.pl/biblio/'.$noticeid);
            if ($result === false) throw new Exception('Impossible d\'appeler le webservice biblio Koha');
            $jsonResult = json_decode($result);
        }
        catch (Exception $e) {
            exit('<p style="color:#FF0000;"><em>Client : </em>Exemplaires '.self::nameClass.' >> Erreur : '.$e->getMessage().'</p>');
        }
        return '<item><institution>'.$institution.'</institution><noticeid>'.$noticeid.'</noticeid>'.$this->formatResult($jsonResult->exemplaires, 'copyDetails').'</item>';
    }
	
    public function launchExportISO($sPathCall, $sPathExport, $sTypeExport, $aAllowedExportTime) {
        $etablissement = strtolower($this->getCodeBib($sPathExport));
        if (empty($sTypeExport)) $sTypeExport = 'diff';
        if (file_exists($sPathCall.'export_diff.mrc')) {
            $pathNamefile = $sPathCall.'export_diff.mrc';
            $namefile = 'export_diff.mrc';
        }
        else if (file_exists($sPathCall.'export_full.mrc')) {
            $sTypeExport = 'full';
            $pathNamefile = $sPathCall.'export_full.mrc';
            $namefile = 'export_full.mrc';
        }
        else {
            $error = 0;
            $namefile = '';
        }
        
        if ($error == 0 && !empty($namefile)) {
            $namefile = date("Ymd-His");
            //Vérification que le fichier n'est pas en train d'arriver
            $fileSize = filesize($pathNamefile);
            sleep(2);
            $newFileSize = filesize($pathNamefile);
            if ($newFileSize == $fileSize) {
                rename($pathNamefile, $sPathExport.$namefile.'.iso');
                $this->createXMLExport($sPathExport, $namefile, $etablissement, $fileSize);
            }
            else {
                $namefile = '';
            }
        }

        $result = array();
        $result['error'] = $error;
        $result['namefile'] = $namefile;
        $result['export'] = $sTypeExport;
        $result['fullExportPath'] = $sPathExport;
        return $result;
    }

    private function createXMLExport($pathExport, $nameFile, $idClient, $fileSize) {
        list($date, $heure) = explode("-", $nameFile);
        $nbNotices = ceil($fileSize/1000); //calcul environ du nombre de notices
        $xmlExport = new SimpleXMLElement('<?xml version="1.0" encoding="utf8"?><Root></Root>');
        $xmlExport->addChild('Etablissement', $idClient);
        $debutNode = $xmlExport->addChild('Debut');
        $debutNode->addChild('Date', $date);
        $debutNode->addChild('Heure', $heure);
        $finNode = $xmlExport->addChild('Fin');
        $finNode->addChild('Date', $date);
        $finNode->addChild('Heure', $heure);
        $contenuNode = $xmlExport->addChild('Contenu');
        $contenuNode->addChild('Nb_Notices', $nbNotices);
        $xmlExport->saveXML($pathExport.$nameFile.'.xml');
    }
    
    //Mise à jour du XML renvoyé à la fin de l'opération d'export ISO et écriture de l'action dans un fichier
    public function updateXML($sPath, $sXML, $sTypeExport, $path = './', $dateserveur) {
        $sXML = $sPath.$sXML.'.xml';
        $xmlResult = new SimpleXMLElement($sXML, 0, true);
        if (!isset($dateserveur) || empty($dateserveur)) $dateserveur = $xmlResult->Fin->Date.$xmlResult->Fin->Heure;
        $xmlResultImport = $xmlResult->addChild('Import');
        $xmlResultImport->addChild('Format', 'iso2709koha');
        $xmlResultImport->addChild('Type', $sTypeExport);
        $xmlResultExport = $xmlResult->addChild('Export');
        $xmlResultExport->addChild('Format', 'solr');
        $xmlResult->addChild('Seq', 1);
        $xmlResult->asXML($sXML);

        //Ajout dans un log de la dernière opération effectuée
        file_put_contents($sPath.'exports_'.$sTypeExport.'.log', 'iso2709koha:1:'.$dateserveur.PHP_EOL, FILE_APPEND);
        if ($sTypeExport == 'full' && file_exists($sPath.'exports_diff.log')) unlink($sPath.'exports_diff.log'); //Suppression du log diff car un full a été fait
        return (string)$xmlResult->Etablissement;
    }

    public function nextCompleteExportISO($sPath) {
        return null;
    }

    //Récupère le code de l'établissement
    private function getCodeBib($sPath) {
        $codeBib = '';
        $sPath = substr($sPath, 0, -1);
        $sPath = str_replace('\\', '/', $sPath);
        $codeBib = substr($sPath, strrpos($sPath, '/') + 1);
        return $codeBib;
    }

    public function getDateServeur(){
        $date_serveur="";
        return $date_serveur;
    }
    
    //Formatage de la réponse pour le serveur
    private function formatResult($oResult, $sAction, $sTempVar = '') {
        switch($sAction) {
            case 'copyDetails':
                $oXMLreturn = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><root></root>');
                $noticeNode = $oXMLreturn->addChild('Notice');
                $unimarcNode = $noticeNode->addChild('Unimarc');
                foreach ($oResult as $exemplaireObj) {
                    $F941node = $unimarcNode->addChild('F941');
                    $F941node->addChild('SFa', $exemplaireObj->barcode);
                    if ($exemplaireObj->notforloan != 0 && $exemplaireObj->notforloan != 5 && ($exemplaireObj->damaged == 1 || $exemplaireObj->itemlost != 0)) {
                        $F941node->addChild('SFo', 6);
                        if ($exemplaireObj->notforloan != 0) {
                            $F941node->addChild('SFn', $this->getLocalValueNotLoan($exemplaireObj->notforloan));
                        }
                        elseif ($exemplaireObj->damaged == 1) {
                            $F941node->addChild('SFn', 'Endommagé');
                        }
                        elseif ($exemplaireObj->itemlost != 0) {
                            $F941node->addChild('SFn', $this->getLocalValueLost($exemplaireObj->itemlost));
                        }
                    }
                    elseif ($exemplaireObj->onloan != null) {
                        $F941node->addChild('SFo', 4);
                        $dueDate = new DateTime($exemplaireObj->date_due);
                        $F941node->addChild('SFq', $dueDate->format("Ymd"));
                    }
                    else {
                        $F941node->addChild('SFo', 1);
                    }
                }
                $noticeNode->addChild('Reservation', 'F');
                $noticeNode->addChild('ReservationCode', 301);
                return $oXMLreturn->Notice->asXML();
                break;
            default:
                return 'Commande inconnue';
        }
        return $oXMLreturn->asXML();
    }

    private function getLocalValueNotLoan($value) {
        $tabValues = array('5' => 'En nouveautés',
                           '0' => 'En rayon',
                           '2' => 'En reliure ou réparation',
                           '1' => 'En traitement',
                           '4' => 'Non disponible');
        return isset($tabValues[$value]) ? $tabValues[$value] : $value;
    }
    
    private function getLocalValueLost($value) {
        $tabValues = array('1' => 'Manquant',
                           '0' => 'Non perdu ou manquant',
                           '2' => 'Perdu');
        return isset($tabValues[$value]) ? $tabValues[$value] : $value;
    }
    
    public function getUserLoans($userInt, $serialized=false) {
        return null;
    }

    public function getUserLoansHistory($userInt, $serialized=false) {
        return null;
    }
    
    public function getUserBookingsHistory($userInt) {
        return null;
    }

    public function updateAccount($formDatas) {
        return null;
    }
    
    public function updateGroupAccount($formDatas) {
        return null;
    }

    public function userLostPassword($mail) {
        return null;
    }

    public function sendMessage($userInt, $mailId, $action, $objet, $text, $suggTitle, $suggAuthor, $suggEditor, $suggDocType) {
        return null;
    }

    public function reserveElectronicals($idElectronicals, $mode, $userInt) {
        return null;
    }

    public function accountDetails($userInt) {
        return null;
    }

    public function login($user, $pass, $ldap = false) {
        return null;
    }

    public function prolongLoan($id, $userid = "") {
        return null;
    }

    public function reserveCancel($resid, $userInt) {
        return null;
    }

    public function reserveDocument($userInt, $idNotice, $site) {
        return null;
    }

    public function reserveInfo($userInt, $idNotice) {
        return null;
    }

}
