<?php

include '../src/openkm/OpenKM.php';

ini_set('display_errors', true);
error_reporting(E_ALL);

use openkm\OKMWebServicesFactory;
use openkm\OpenKM;
use openkm\util\PathUtils;

class ExampleDocument {

    const HOST = "http://localhost:8888/openkm/";
    const USER = "okmAdmin";
    const PASSWORD = "admin";

    private $ws;

    public function __construct() {
        $this->ws = OKMWebServicesFactory::build(self::HOST);
    }

    public function testCreateDocument() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $fileName = dirname(__FILE__) . '/files/test.pdf';
            $document = $this->ws->document->createDocument('f93ac8df-e83b-487f-9a14-0af9e910a818', 'test.pdf', file_get_contents($fileName));
            var_dump($document);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testDeleteDocument() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $this->ws->document->deleteDocument('5b37c508-b2be-4429-ba5e-acc96089c6a9');
            echo 'deleted';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetDocumentProperties() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $document = $this->ws->document->getDocumentProperties('7e12a9ff-95b2-4945-bf5f-1bb709d89c14');
            var_dump($document);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetContent($method) {
        $this->ws->login(self::USER, self::PASSWORD);
        $content = $this->ws->document->getContent('b02877cc-bc71-4be9-9bfb-2e50b1732fd3');
        switch ($method) {
            case 1:
                $file = fopen(dirname(__FILE__) . '/files/logo_download.png', 'w+');
                fwrite($file, $content);
                fclose($file);
                echo 'download correct';
                break;
            case 2:
                ob_clean();
                $document = $this->ws->document->getDocumentProperties('b02877cc-bc71-4be9-9bfb-2e50b1732fd3');
                $name = PathUtils::getName($document->getPath());
                header("Cache-Control:  maxage=1");
                header("Pragma: public");
                header("Content-Type: " . $document->getMimeType());
                header('Content-Disposition: attachment; filename="' . $name . '"');
                header("Content-Length: " . strlen($content));
                echo $content;
                break;
        }
    }

    public function testGetContentByVersion($method) {
        $this->ws->login(self::USER, self::PASSWORD);
        $content = $this->ws->document->getContentByVersion('b02877cc-bc71-4be9-9bfb-2e50b1732fd3', 1.2);
        switch ($method) {
            case 1:
                $file = fopen(dirname(__FILE__) . '/files/logo_download_version.png', 'w+');
                fwrite($file, $content);
                fclose($file);
                echo 'download correct';
                break;
            case 2:
                $document = $this->ws->document->getDocumentProperties('b02877cc-bc71-4be9-9bfb-2e50b1732fd3');
                header('Expires', 'Sat, 6 May 1971 12:00:00 GMT');
                header('Cache-Control', 'max-age=0, must-revalidate');
                header('Cache-Control', 'post-check=0, pre-check=0');
                header('Pragma', 'no-cache');
                header('Content-Type: ' . $document->getMimeType());
                header('Content-Disposition: attachment; filename="' . substr($document->getPath(), strrpos($document->getPath(), '/') + 1) . '"');
                echo $content;
                break;
        }
    }

    public function testGetExtractedText() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $text = $this->ws->document->getExtractedText('7e12a9ff-95b2-4945-bf5f-1bb709d89c14');
            var_dump($text);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetThumbnail($method) {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $content = $this->ws->document->getThumbnail('7e12a9ff-95b2-4945-bf5f-1bb709d89c14');
            switch ($method) {
                case 1:
                    $file = fopen(dirname(__FILE__) . '/files/thumbnail.png', 'w+');
                    fwrite($file, $content);
                    fclose($file);
                    echo 'download correct';
                    break;
                case 2:
                    header('Expires', 'Sat, 6 May 1971 12:00:00 GMT');
                    header('Cache-Control', 'max-age=0, must-revalidate');
                    header('Cache-Control', 'post-check=0, pre-check=0');
                    header('Pragma', 'no-cache');
                    header('Content-Type: ' . \openkm\util\MimeTypeConfig::MIME_PNG);
                    header('Content-Disposition: attachment; filename="thumbnail.png"');
                    echo $content;
                    break;
            }
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetDocumentChildren() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $documents = $this->ws->document->getDocumentChildren('f93ac8df-e83b-487f-9a14-0af9e910a818');
            foreach ($documents as $document) {
                var_dump($document);
            }
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testRenameDocument() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $document = $this->ws->document->renameDocument('b02877cc-bc71-4be9-9bfb-2e50b1732fd3', 'logo_rename.png');
            var_dump($document);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testSetProperties() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $document = $this->ws->getDocumentProperties('604e17e8-3285-4e8a-910c-c99ee4e44262');
            $document->setTitle('Logo');
            $document->setDescription('some description');
            $document->setLanguage('es');
            //Keywords
            $keywords = array();
            $keywords[] = 'test';
            $document->setKeywords($keywords);
            //Categories
            $categories = array();
            $category = $this->ws->getFolderProperties('/okm:categories/test');
            $categories[] = $category;
            $document->setCategories($categories);

            $this->ws->setProperties($document);
            echo 'updated';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testSetLanguage() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $this->ws->setLanguage('/okm:root/SDK4PHP/document.odt', 'es');
            echo 'updated';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testSeDocumenttTitle() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $this->ws->setDocumentTitle('/okm:root/SDK4PHP/document.odt', 'Some title here');
            echo 'updated';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testCheckout() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $this->ws->checkout('/okm:root/SDK4PHP/logo.png');
            // At this point the document is locked for other users except for the user who executed the action
            echo 'correct';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testCancelCheckout() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            // At this point the document is locked for other users except for the user who executed the action
            $this->ws->cancelCheckout('/okm:root/SDK4PHP/logo.png');
            // At this point other users are allowed to execute a checkout and modify the document
            echo 'correct';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testForceCancelCheckout() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            // At this point the document is locked for other users except for the user who executed the action
            $this->ws->forceCancelCheckout('/okm:root/SDK4PHP/logo.png');
            // At this point other users are allowed to execute a checkout and modify the document
            echo 'correct';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testIsCheckedOut() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            var_dump($this->ws->isCheckedOut('/okm:root/SDK4PHP/logo.png'));
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testCheckin() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $fileName = dirname(__FILE__) . '/files/logo.png';
            $version = $this->ws->checkin('/okm:root/SDK4PHP/logo.png', file_get_contents($fileName), "optional some comment", 1);
            var_dump($version);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetVersionHistory() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $versions = $this->ws->getVersionHistory('/okm:root/SDK4PHP/logo.png');
            foreach ($versions as $version) {
                var_dump($version);
            }
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testLock() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $lockInfo = $this->ws->lock('/okm:root/SDK4PHP/logo.png');
            var_dump($lockInfo);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testUnlock() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $this->ws->unlock('/okm:root/SDK4PHP/logo.png');
            echo 'unlock';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testForceUnlock() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $this->ws->forceUnlock('/okm:root/SDK4PHP/logo.png');
            echo 'forceUnlock';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testIsLocked() {
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            echo "Is document locked: ";
            var_dump($this->ws->isLocked('/okm:root/SDK4PHP/logo.png'));
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetLockInfo() {
        try {
            var_dump($this->ws->getLockInfo('/okm:root/SDK4PHP/logo.png'));
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testPurgeDocument() {
        try {
            $this->ws->purgeDocument('/okm:root/SDK4PHP/logo.png');
            echo 'purgeDocument';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testMoveDocument() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $this->ws->document->moveDocument('b02877cc-bc71-4be9-9bfb-2e50b1732fd3', '55102c84-e4f5-4cbc-a3d1-cf1896367752');
            echo 'moveDocument';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testCopyDocument() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $document = $this->ws->document->copyDocument('b02877cc-bc71-4be9-9bfb-2e50b1732fd3', '55102c84-e4f5-4cbc-a3d1-cf1896367752', 'new_logo.png');
            var_dump($document);
            echo 'copyDocument';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testRestoreVersion() {
        try {
            $this->ws->restoreVersion('/okm:root/SDK4PHP/logo.png', '1.1');
            echo 'restoreVersion';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testPurgeVersionHistory() {
        try {
            // Version history has version 1.3,1.2,1.1 and 1.0
            $this->ws->purgeVersionHistory('/okm:root/SDK4PHP/logo.png');
            // Version history has only version 1.3
            echo 'purgeVersionHistory';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetVersionHistorySize() {
        try {
            $units = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];

            $bytes = $this->ws->getVersionHistorySize('/okm:root/SDK4PHP/logo.png');
            $value = "";

            for ($i = 6; $i > 0; $i--) {
                $step = pow(1024, $i);
                if ($bytes > $step) {
                    $value = number_format($bytes / $step, 2) . ' ' . $units[$i];
                }
                if (empty($value)) {
                    $value = $bytes . ' ' . $units[0];
                }
            }
            echo $value;
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testIsValidDocument() {
        try {
            echo '/okm:root/sdk/logo.png -> ';
            var_dump($this->ws->document->isValidDocument('d701c503-87fc-4a9e-829e-478dc375eb83'));
            echo '<br/>';
            echo '/okm:root -> ';
            var_dump($this->ws->document->isValidDocument('74aa0a29-97f8-4e2e-9c60-880eb627f05e'));
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetDocumentPath() {
        try {
            var_dump($this->ws->getDocumentPath("8b559709-3c90-4c26-b181-5192a17362b2"));
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetDetectedLanguages() {
        try {
            var_dump($this->ws->getDetectedLanguages());
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testExtendedDocumentCopy() {
        try {
            $this->ws->extendedDocumentCopy('/okm:root/SDK4PHP/logo.png', '/okm:root/SDK4PHP/tmp', '', true, true, true, true, true);
            echo 'extendedDocumentCopy';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testCreateFromTemplate() {
        try {
            $formElements = array();

            $name = new \openkm\bean\form\Input();
            $name->setName('okp:tpl.name');
            $name->setValue('Some name');
            $formElements[] = $name;

            $birdDate = new \openkm\bean\form\Input();
            $birdDate->setName('okp:tpl.bird_date');
            // Value must be converted to String ISO 8601 compliant
            $birdDate->setValue(date('Ymdhis'));
            $formElements[] = $birdDate;

            $language = new \openkm\bean\form\Select();
            $language->setName('okp:tpl.language');

            $options = array();
            $option = new \openkm\bean\form\Option();
            $option->setValue('php');
            $option->setSelected(true);
            $options[] = $option;
            $language->setOptions($options);
            $formElements[] = $language;

            $document = $this->ws->createFromTemplate('/okm:templates/tpl.pdf', '/okm:root/SDK4PHP/test.pdf', false, false, true, false, false, $formElements);
            var_dump($document);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testCreateFromTemplateSimple() {
        try {
            $properties = array();

            $name = new \openkm\bean\SimplePropertyGroup();
            $name->setName('okp:tpl.name');
            $name->setValue('Some name');
            $properties[] = $name;

            $birdDate = new \openkm\bean\SimplePropertyGroup();
            $birdDate->setName('okp:tpl.bird_date');
            // Value must be converted to String ISO 8601 compliant
            $birdDate->setValue(date('Ymdhis'));
            $properties[] = $birdDate;

            $language = new \openkm\bean\SimplePropertyGroup();
            $language->setName('okp:tpl.language');
            $language->setValue('php');
            $properties[] = $language;

            $document = $this->ws->createFromTemplateSimple('/okm:templates/tpl.pdf', '/okm:root/SDK4PHP/test.pdf', false, false, true, false, false, $properties);
            var_dump($document);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testUpdateFromTemplate() {
        try {
            $formElements = array();

            $name = new \openkm\bean\form\Input();
            $name->setName('okp:tpl.name');
            $name->setValue('Update name');
            $formElements[] = $name;

            $birdDate = new \openkm\bean\form\Input();
            $birdDate->setName('okp:tpl.bird_date');
            // Value must be converted to String ISO 8601 compliant
            $birdDate->setValue(date('Ymdhis'));
            $formElements[] = $birdDate;

            $language = new \openkm\bean\form\Select();
            $language->setName('okp:tpl.language');

            $options = array();
            $option = new \openkm\bean\form\Option();
            $option->setValue('go');
            $option->setSelected(true);
            $options[] = $option;
            $language->setOptions($options);
            $formElements[] = $language;

            $document = $this->ws->updateFromTemplate('/okm:templates/tpl.pdf', '/okm:root/SDK4PHP/test.pdf', $formElements);
            var_dump($document);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testUpdateFromTemplateSimple() {
        try {
            $properties = array();

            $name = new \openkm\bean\SimplePropertyGroup();
            $name->setName('okp:tpl.name');
            $name->setValue('Update name');
            $properties[] = $name;

            $birdDate = new \openkm\bean\SimplePropertyGroup();
            $birdDate->setName('okp:tpl.bird_date');
            // Value must be converted to String ISO 8601 compliant
            $birdDate->setValue(date('Ymdhis'));
            $properties[] = $birdDate;

            $language = new \openkm\bean\SimplePropertyGroup();
            $language->setName('okp:tpl.language');
            $language->setValue('go');
            $properties[] = $language;

            $document = $this->ws->updateFromTemplateSimple('/okm:templates/tpl.pdf', '/okm:root/SDK4PHP/test.pdf', $properties);
            var_dump($document);
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetAnnotations() {
        try {
            var_dump($this->ws->getAnnotations('16ac0193-676b-49e6-a65b-d3f847ac4343', '1.2'));
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetDifferences($method) {
        try {
            $content = $this->ws->getDifferences('e34af683-7a8f-447c-98fb-8417b399f8d5', '1.0', '1.1');
            switch ($method) {
                case 1:
                    $file = fopen(dirname(__FILE__) . '/files/text.csv', 'w+');
                    fwrite($file, $content);
                    fclose($file);
                    echo 'download correct';
                    break;
                case 2:
                    $document = $this->ws->getDocumentProperties('/test.csv');
                    header('Expires', 'Sat, 6 May 1971 12:00:00 GMT');
                    header('Cache-Control', 'max-age=0, must-revalidate');
                    header('Cache-Control', 'post-check=0, pre-check=0');
                    header('Pragma', 'no-cache');
                    header('Content-Type: ' . $document->getMimeType());
                    header('Content-Disposition: attachment; filename="' . substr($document->getPath(), strrpos($document->getPath(), '/') + 1) . '"');
                    echo $content;
                    break;
            }
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function testGetCheckedOut() {
        try {
            $documents = $this->ws->getCheckedOut();
            foreach ($documents as $document) {
                var_dump($document);
            }
        } catch (Exception $e) {
            var_dump($e);
        }
    }

    public function download() {
        $content = $this->ws->document->getContent('4eb6317a-95c5-4d69-b31f-6e1887a24140');
        ob_clean();
        $documen = new openkm\bean\Document();
        $document = $this->ws->document->getDocumentProperties('4eb6317a-95c5-4d69-b31f-6e1887a24140');
        $name = PathUtils::getName($document->getPath());
        header("Cache-Control:  maxage=1");
        header("Pragma: public");
        header("Content-Type: " . $document->getMimeType());
        header('Content-Disposition: attachment; filename="' . $name . '"');
        header("Content-Length: " . strlen($content));
        header("Access-Control-Allow-Origin: *");
        echo $content;
    }

    public function testMergePdf() {
        echo '<pre>';
        try {
            $this->ws->login(self::USER, self::PASSWORD);
            $uuids = [];
            $uuids[] = 'cc99978e-7272-4d4f-84e1-23e0a48eb84b';
            $uuids[] = '340e1654-4185-4872-ac1e-faacb1c62acc';
            $uuids[] = 'fdb16465-27c6-48df-85af-0314431f3351';
            $this->ws->document->mergePdf('7d2d3873-e427-4ca6-984c-3accb79574e5', 'test', $uuids);
            echo 'mergePdf';
        } catch (Exception $e) {
            var_dump($e);
        }
    }

}

$openkm = new OpenKM(); //autoload
$exampleDocument = new ExampleDocument();

// $exampleDocument->testCreateDocument();
// $exampleDocument->testDeleteDocument();/
// $exampleDocument->testGetDocumentProperties();
// $exampleDocument->testGetContent(2);
// $exampleDocument->testGetContentByVersion(1);
// $exampleDocument->testGetExtractedText();
// $exampleDocument->testGetThumbnail(1);
// $exampleDocument->testGetDocumentChildren();
// $exampleDocument->testRenameDocument();
// $exampleDocument->testMoveDocument();
// $exampleDocument->testCopyDocument();
$exampleDocument->testMergePdf();
?>