//! Module containing error types used in Garage
use std::fmt;
use std::io;

use thiserror::Error;

use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer};

use crate::data::*;
use crate::encode::debug_serialize;

/// Regroup all Garage errors
#[derive(Debug, Error)]
pub enum Error {
	#[error("IO error: {0}")]
	Io(#[from] io::Error),

	#[error("Hyper error: {0}")]
	Hyper(#[from] hyper::Error),

	#[error("HTTP error: {0}")]
	Http(#[from] http::Error),

	#[error("Invalid HTTP header value: {0}")]
	HttpHeader(#[from] http::header::ToStrError),

	#[error("Network error: {0}")]
	Net(#[from] garage_net::error::Error),

	#[error("DB error: {0}")]
	Db(#[from] garage_db::Error),

	#[error("Messagepack encode error: {0}")]
	RmpEncode(#[from] rmp_serde::encode::Error),
	#[error("Messagepack decode error: {0}")]
	RmpDecode(#[from] rmp_serde::decode::Error),
	#[error("JSON error: {0}")]
	Json(#[from] serde_json::error::Error),
	#[error("TOML decode error: {0}")]
	TomlDecode(#[from] toml::de::Error),

	#[error("Tokio join error: {0}")]
	TokioJoin(#[from] tokio::task::JoinError),

	#[error("Tokio semaphore acquire error: {0}")]
	TokioSemAcquire(#[from] tokio::sync::AcquireError),

	#[error("Tokio broadcast receive error: {0}")]
	TokioBcastRecv(#[from] tokio::sync::broadcast::error::RecvError),

	#[error("Remote error: {0}")]
	RemoteError(String),

	#[error("Timeout")]
	Timeout,

	#[error("Layout not ready")]
	LayoutNotReady,

	#[error("Could not reach quorum of {0} (sets={1:?}). {2} of {3} request succeeded, others returned errors: {4:?}")]
	Quorum(usize, Option<usize>, usize, usize, Vec<String>),

	#[error("Unexpected RPC message: {0}")]
	UnexpectedRpcMessage(String),

	#[error("Corrupt data: does not match hash {0:?}")]
	CorruptData(Hash),

	#[error("Missing block {0:?}: no node returned a valid block")]
	MissingBlock(Hash),

	#[error("{0}")]
	Message(String),
}

impl Error {
	pub fn unexpected_rpc_message<T: Serialize>(v: T) -> Self {
		Self::UnexpectedRpcMessage(debug_serialize(&v))
	}
}

impl From<garage_db::TxError<Error>> for Error {
	fn from(e: garage_db::TxError<Error>) -> Error {
		match e {
			garage_db::TxError::Abort(x) => x,
			garage_db::TxError::Db(x) => Error::Db(x),
		}
	}
}

impl<T> From<tokio::sync::watch::error::SendError<T>> for Error {
	fn from(_e: tokio::sync::watch::error::SendError<T>) -> Error {
		Error::Message("Watch send error".to_string())
	}
}

impl<T> From<tokio::sync::mpsc::error::SendError<T>> for Error {
	fn from(_e: tokio::sync::mpsc::error::SendError<T>) -> Error {
		Error::Message("MPSC send error".to_string())
	}
}

impl<'a> From<&'a str> for Error {
	fn from(v: &'a str) -> Error {
		Error::Message(v.to_string())
	}
}

impl From<String> for Error {
	fn from(v: String) -> Error {
		Error::Message(v)
	}
}

pub trait ErrorContext<T, E> {
	fn err_context<C: std::borrow::Borrow<str>>(self, ctx: C) -> Result<T, Error>;
}

impl<T, E> ErrorContext<T, E> for Result<T, E>
where
	E: std::fmt::Display,
{
	#[inline]
	fn err_context<C: std::borrow::Borrow<str>>(self, ctx: C) -> Result<T, Error> {
		match self {
			Ok(x) => Ok(x),
			Err(e) => Err(Error::Message(format!("{}\n{}", ctx.borrow(), e))),
		}
	}
}

/// Trait to map any error type to `Error::Message`
pub trait OkOrMessage {
	type S;
	fn ok_or_message<M: Into<String>>(self, message: M) -> Result<Self::S, Error>;
}

impl<T, E> OkOrMessage for Result<T, E>
where
	E: std::fmt::Display,
{
	type S = T;
	fn ok_or_message<M: Into<String>>(self, message: M) -> Result<T, Error> {
		match self {
			Ok(x) => Ok(x),
			Err(e) => Err(Error::Message(format!("{}: {}", message.into(), e))),
		}
	}
}

impl<T> OkOrMessage for Option<T> {
	type S = T;
	fn ok_or_message<M: Into<String>>(self, message: M) -> Result<T, Error> {
		match self {
			Some(x) => Ok(x),
			None => Err(Error::Message(message.into())),
		}
	}
}

// Custom serialization for our error type, for use in RPC.
// Errors are serialized as a string of their Display representation.
// Upon deserialization, they all become a RemoteError with the
// given representation.

impl Serialize for Error {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: Serializer,
	{
		serializer.serialize_str(&format!("{}", self))
	}
}

impl<'de> Deserialize<'de> for Error {
	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
	where
		D: Deserializer<'de>,
	{
		deserializer.deserialize_string(ErrorVisitor)
	}
}

struct ErrorVisitor;

impl<'de> Visitor<'de> for ErrorVisitor {
	type Value = Error;

	fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
		write!(formatter, "a string that represents an error value")
	}

	fn visit_str<E>(self, error_msg: &str) -> Result<Self::Value, E> {
		Ok(Error::RemoteError(error_msg.to_string()))
	}

	fn visit_string<E>(self, error_msg: String) -> Result<Self::Value, E> {
		Ok(Error::RemoteError(error_msg))
	}
}
