<?php

namespace openkm\impl;

use Httpful\Exception\ConnectionErrorException;
use Httpful\Request;
use openkm\definition\BaseNode;
use openkm\exception\AccessDeniedException;
use openkm\exception\DatabaseException;
use openkm\exception\PathNotFoundException;
use openkm\exception\RepositoryException;
use openkm\exception\UnknowException;
use openkm\util\FormatUtils;
use openkm\util\Status;
use openkm\util\TypeException;
use openkm\util\UriHelper;

class NodeImpl extends ClientImpl implements BaseNode {

    public function generateDownloadToken($uuid, $preview) {
        try {
            $uri = UriHelper::getUri($this->host, FormatUtils::format(UriHelper::NODE_POST_DOWNLOAD_TOKEN, ['uuid' => $uuid]));
            if ($preview) {
                $uri .= '?preview=true';
            } else {
                $uri .= '?preview=false';
            }

            $client = Request::post($uri);
            $response = $this->getClientWithHTMLResponse($client);
            if ($response->code == Status::OK) {
                return (string)$response->body;
            } else {
                $restException = new \openkm\bean\RestException();
                $restException = $this->phpRestException(json_decode($response->body));
                if ($restException->getSimpleName() != '') {
                    if ($restException->getSimpleName() == TypeException::PATH_NOT_FOUND_EXCEPTION) {
                        throw new PathNotFoundException($restException->getMessage());
                    } else if ($restException->getSimpleName() == TypeException::ACCESS_DENIED_EXCEPTION) {
                        throw new AccessDeniedException($restException->getMessage());
                    } else if ($restException->getSimpleName() == TypeException::REPOSITORY_EXCEPTION) {
                        throw new RepositoryException($restException->getMessage());
                    } else if ($restException->getSimpleName() == TypeException::DATABASE_EXCEPTION) {
                        throw new DatabaseException($restException->getMessage());
                    } else {
                        throw new UnknowException($restException->getMessage());
                    }
                } else {
                    throw new UnknowException("HTTP error code " . $response->code . ": " . $response->body);
                }
            }
        } catch (ConnectionErrorException $cee) {
            throw new ConnectionErrorException('ConnectionErrorException: ' . $cee->getMessage());
        }
    }
}
