use failure::{Error, Fail};
use std::sync::Arc;

use tokio::sync::mpsc::error::SendError as MpscSendError;
use tokio::sync::oneshot::error::RecvError as OneShotRecvError;

#[derive(Debug, Fail)]
pub enum ShardError {
    #[fail(display = "shard is at capacity, and is unable to evict any records")]
    ShardAtCapacity,

    #[fail(display = "upstream error: {:?}", error)]
    UpstreamError { error: UpstreamError },

    #[fail(display = "the shard is no longer running")]
    ShardGone,
}

impl From<OneShotRecvError> for ShardError {
    fn from(_error: OneShotRecvError) -> Self {
        ShardError::ShardGone
    }
}

impl<T> From<MpscSendError<T>> for ShardError {
    fn from(_error: MpscSendError<T>) -> Self {
        ShardError::ShardGone
    }
}

#[derive(Debug, Fail, Clone)]
pub enum UpstreamError {
    #[fail(display = "operation aborted")]
    OperationAborted,

    #[fail(display = "key not found")]
    KeyNotFound,

    #[fail(display = "driver error: {:?}", error)]
    DriverError { error: Arc<Error> },
}

impl UpstreamError {
    pub fn is_not_found(&self) -> bool {
        match self {
            UpstreamError::KeyNotFound => true,
            _ => false,
        }
    }
}

impl From<Error> for UpstreamError {
    fn from(error: Error) -> Self {
        UpstreamError::DriverError {
            error: Arc::new(error),
        }
    }
}

#[cfg(feature = "cassandra")]
impl From<cassandra_cpp::Error> for UpstreamError {
    fn from(error: cassandra_cpp::Error) -> Self {
        UpstreamError::DriverError {
            error: Arc::new(failure::SyncFailure::new(error).into()),
        }
    }
}

#[cfg(feature = "cassandra")]
impl From<cassandra_cpp::Error> for ShardError {
    fn from(error: cassandra_cpp::Error) -> Self {
        let upstream_error: UpstreamError = error.into();
        upstream_error.into()
    }
}

impl Into<ShardError> for UpstreamError {
    fn into(self) -> ShardError {
        ShardError::UpstreamError { error: self }
    }
}
