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

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

#[derive(Copy, Clone, Eq, PartialEq, Debug, Fail)]
pub enum OpmlErrorKind {
    #[fail(display = "Failed to parse xml")]
    Xml,
    #[fail(display = "No body tag found")]
    Body,
    #[fail(display = "No outline tag inside body found")]
    Empty,
    #[fail(display = "No valid Utf8 byte sequence")]
    Utf8,
    #[fail(display = "Unknown Error")]
    Unknown,
}

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

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

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

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

impl From<Context<OpmlErrorKind>> for OpmlError {
    fn from(inner: Context<OpmlErrorKind>) -> OpmlError {
        OpmlError { inner }
    }
}

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