use failure::{Backtrace, Context, Fail};
use std::fmt;

#[derive(Debug)]
pub struct ModelError {
    inner: Context<ModelErrorKind>,
}

#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
pub enum ModelErrorKind {
    #[fail(display = "IO error")]
    IO,
    #[fail(display = "IO error")]
    Url,
    #[fail(display = "Error parsing Json")]
    Json,
    #[fail(display = "Error creating proxy object")]
    Proxy,
    #[fail(display = "Unknown Error")]
    Unknown,
}

impl Fail for ModelError {
    fn cause(&self) -> Option<&dyn Fail> {
        self.inner.cause()
    }

    fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace()
    }
}

impl fmt::Display for ModelError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.inner, f)
    }
}

impl ModelError {
    pub fn kind(&self) -> ModelErrorKind {
        *self.inner.get_context()
    }
}

impl From<ModelErrorKind> for ModelError {
    fn from(kind: ModelErrorKind) -> ModelError {
        ModelError { inner: Context::new(kind) }
    }
}

impl From<Context<ModelErrorKind>> for ModelError {
    fn from(inner: Context<ModelErrorKind>) -> ModelError {
        ModelError { inner }
    }
}
