pub mod error;
pub mod miner;
pub mod params;
pub mod stratum_error;
pub mod traits;
use crate::params::{ClientParam, PoolParam};
pub use crate::stratum_error::StratumError;
use crate::traits::{PoolParams, StratumParams};
pub use error::Error;
pub use miner::{MinerAuth, MinerInfo, MinerJobStats};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub type Result<T> = std::result::Result<T, Error>;

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
pub enum PoolPacket<PP, SP>
where
    PP: PoolParams,
    SP: StratumParams,
{
    Request(Request<PoolParam<PP, SP>>),
    Response(Response<PoolParam<PP, SP>>),
}

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
pub enum ClientPacket<PP, SP>
where
    PP: PoolParams,
    SP: StratumParams,
{
    Request(Request<ClientParam<PP, SP>>),
    Response(Response<ClientParam<PP, SP>>),
}

#[derive(Serialize, Deserialize)]
pub struct Request<T> {
    pub id: String,
    pub method: StratumMethod,
    pub params: T,
}

#[derive(Serialize, Deserialize)]
pub struct Response<T> {
    pub id: String,
    pub method: StratumMethod,
    pub result: Option<T>,
    pub error: Option<StratumError>,
}

#[derive(Debug)]
pub enum StratumMethod {
    //Sending and receiving
    Authorize,
    Submit,
    Subscribe,
    Notify,
    SetDifficulty,

    //Future methods potentially not implemented yet.
    Unknown(String),
}

impl Serialize for StratumMethod {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(match *self {
            StratumMethod::Authorize => "authorize",
            StratumMethod::Submit => "submit",
            StratumMethod::Subscribe => "subscribe",
            StratumMethod::Notify => "notify",
            StratumMethod::SetDifficulty => "set_difficulty",
            StratumMethod::Unknown(ref s) => s,
        })
    }
}

impl<'de> Deserialize<'de> for StratumMethod {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(match s.as_str() {
            "authorize" => StratumMethod::Authorize,
            "submit" => StratumMethod::Submit,
            "subscribe" => StratumMethod::Subscribe,
            "notify" => StratumMethod::Notify,
            "set_difficulty" => StratumMethod::SetDifficulty,
            _ => StratumMethod::Unknown(s),
        })
    }
}
