use context::Context;
use std::{
    fmt::{Debug, Display},
    num::ParseIntError,
    sync::Arc,
};

pub type Result<R> = std::result::Result<R, Error>;

pub struct Error {
    pub ctx: Option<Arc<Context>>,
    pub message: String,
}

impl std::error::Error for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.ctx {
            Some(ctx) => write!(f, "[{}] {}", ctx.id(), self.message),
            None => write!(f, "{}", self.message),
        }
    }
}

impl Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.ctx {
            Some(ctx) => write!(f, "[{}] {}", ctx.id(), self.message),
            None => write!(f, "{}", self.message),
        }
    }
}

impl Error {
    pub fn new(message: String) -> Self {
        Error { ctx: None, message }
    }

    pub fn ctx(mut self, ctx: Arc<Context>) -> Self {
        ctx.push_phase("fts_error", Some(self.message.clone()));
        self.ctx = Some(ctx);
        self
    }
}

impl From<reqwest::Error> for Error {
    fn from(err: reqwest::Error) -> Self {
        Error::new(err.to_string())
    }
}

impl From<url::ParseError> for Error {
    fn from(err: url::ParseError) -> Self {
        Error::new(err.to_string())
    }
}

impl From<ParseIntError> for Error {
    fn from(err: ParseIntError) -> Self {
        Error::new(err.to_string())
    }
}
