/* Copyright 2020, Michele Santullo
 * This file is part of orotool.
 *
 * Orotool 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 3 of the License, or
 * (at your option) any later version.
 *
 * Orotool 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 Orotool.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "api_nap_exception.hpp"
#include "nap/http_response.hpp"
#include <string>
#include <algorithm>
#include <cassert>

namespace oro {
namespace {
std::size_t append_to_char_arary (std::string_view in, char* out, std::size_t offs, std::size_t capacity) {
	assert(capacity >= offs + 1);

	const std::size_t out_size = std::min(in.size(), capacity - offs - 1);
	std::copy(in.begin(), in.begin() + out_size, out + offs);
	out[out_size] = '\0';

	return offs + out_size;
}
} //unnamed namespace

ServerError::ServerError (const nap::HttpResponse& resp) :
	std::runtime_error(
		std::string("Server replied: ") + std::to_string(resp.code) + " (" +
			std::string(resp.http_ver) + ", \"" + std::string(resp.code_desc) +
			"\")"
	),
	m_err_code(static_cast<int>(resp.code))
{
}

int ServerError::error_code() const noexcept {
	return m_err_code;
}

ContentTypeError::ContentTypeError (std::string_view type, std::string_view subtype) :
	std::runtime_error(
		std::string("Unexpected content-type received: \"") +
		std::string(type) + "/" + std::string(subtype) + "\""
	)
{
	std::size_t offs = 0;
	offs = append_to_char_arary(type, m_content_type.data(), offs, m_content_type.size());
	offs = append_to_char_arary("/", m_content_type.data(), offs, m_content_type.size());
	offs = append_to_char_arary(subtype, m_content_type.data(), offs, m_content_type.size());
}

std::string_view ContentTypeError::content_type() const noexcept {
	return {m_content_type.data()};
}

ConnectionError::ConnectionError (const std::string& reason, unsigned int code) :
	std::runtime_error("Connection error: " + reason),
	m_curl_code(code)
{
}

unsigned int ConnectionError::curl_code() const {
	return m_curl_code;
}

} //namespace oro
