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

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

#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
pub enum PortalErrorKind {
    #[fail(display = "Unknown Error")]
    Unknown,
    #[fail(display = "Error reading from db")]
    DB,
}

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

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

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

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

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

impl From<Context<PortalErrorKind>> for PortalError {
    fn from(inner: Context<PortalErrorKind>) -> PortalError {
        PortalError { inner }
    }
}

impl From<Error> for PortalError {
    fn from(_: Error) -> PortalError {
        PortalError {
            inner: Context::new(PortalErrorKind::Unknown),
        }
    }
}
