use futures::channel::mpsc::SendError;
use std::fmt;

#[derive(Debug)]
pub enum Error {
    NotAuthorized,
    StreamClosed,
    MethodDoesntExist,
    #[cfg(feature = "websockets")]
    Websocket(async_tungstenite::tungstenite::Error),
    Json(serde_json::error::Error),
    Io(std::io::Error),
    MesssageSend(SendError),
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Error {
        Error::Io(e)
    }
}

impl From<serde_json::error::Error> for Error {
    fn from(e: serde_json::error::Error) -> Error {
        Error::Json(e)
    }
}

impl From<SendError> for Error {
    fn from(e: SendError) -> Error {
        Error::MesssageSend(e)
    }
}

#[cfg(feature = "websockets")]
impl From<async_tungstenite::tungstenite::Error> for Error {
    fn from(e: async_tungstenite::tungstenite::Error) -> Error {
        Error::Websocket(e)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            Error::NotAuthorized => write!(f, "Stratum User not authorized"),
            Error::StreamClosed => write!(f, "Stratum Stream closed"),
            Error::MethodDoesntExist => write!(f, "Stratum Method Doesn't Exist"),
            Error::Json(ref e) => write!(f, "JSON error: {}", e),
            Error::Io(ref e) => write!(f, "IO Error: {}", e),
            Error::MesssageSend(ref e) => write!(f, "Channel Send Error: {}", e),
            #[cfg(feature = "websockets")]
            Error::Websocket(ref e) => write!(f, "Websocket Error: {}", e),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Error::NotAuthorized => None,
            Error::StreamClosed => None,
            Error::MethodDoesntExist => None,
            Error::Json(ref e) => Some(e),
            Error::Io(ref e) => Some(e),
            Error::MesssageSend(ref e) => Some(e),
            #[cfg(feature = "websockets")]
            Error::Websocket(ref e) => Some(e),
        }
    }
}
