use std::fmt;

const KAMELEOON_SDK: &str = "Kameleoon SDK:";

pub(crate) type KErr = KameleoonError;

#[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq))]
pub struct KameleoonError {
    code: ErrorCode,
    message: String,
}

impl KameleoonError {
    // Helper constructor for convenience
    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            code: code,
            message: message.into(),
        }
    }

    pub(crate) fn new_internal(message: impl Into<String>) -> Self {
        Self {
            code: ErrorCode::Internal,
            message: message.into(),
        }
    }

    pub fn code(&self) -> ErrorCode {
        return self.code;
    }

    pub fn message(&self) -> &str {
        return &self.message;
    }
}

impl fmt::Display for KameleoonError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} {}", KAMELEOON_SDK, self.message)
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ErrorCode {
    Initialization = 0,
    FeatureNotFound = 1,
    FeatureExperimentNotFound = 2,
    FeatureVariationNotFound = 3,
    FeatureVariableNotFound = 4,
    FeatureEnvironmentDisabled = 5,
    SiteCodeIsEmpty = 6,
    ConfigCredentialsInvalid = 7,
    VisitorCodeInvalid = 8,
    FeatureRuleNotFound = 9,
    InvalidSimVarCookieFormat = 10,
    Timeout = 252,
    Network = 253,
    Internal = 254,
    Unknown = 255,
}

impl From<&str> for KameleoonError {
    fn from(str: &str) -> Self {
        KameleoonError::new(ErrorCode::Unknown, str.to_owned())
    }
}

// impl<T: Error> From<T> for KameleoonError {
//     fn from(err: T) -> Self {
//         KameleoonError::new(ErrorCode::Unknown, err.to_string())
//     }
// }

impl From<String> for KameleoonError {
    fn from(str: String) -> Self {
        KameleoonError::new(ErrorCode::Unknown, str)
    }
}
