use std::fmt::Display;

use base62::decode;
use serde::{Deserialize, Deserializer, Serialize, de::Visitor};
use tritools::id::Id as NewId;
use uuid::Uuid;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Id {
    Next(NewId),
    Legacy(usize),
}

impl Id {
    /// Create a new ID.
    pub fn new() -> Self {
        Self::Next(NewId::new())
    }

    /// Get the ID as a usize.
    pub fn as_usize(&self) -> usize {
        match self {
            Self::Next(x) => x.0.as_u128() as usize,
            Self::Legacy(x) => *x,
        }
    }

    /// Get the printable form of the ID. (base62 UUID)
    pub fn printable(&self) -> String {
        match self {
            Self::Next(x) => x.printable(),
            Self::Legacy(x) => x.to_string(),
        }
    }

    /// Serialize using `serde_json`. Surrounding quotes removed.
    pub fn serialize(&self) -> String {
        serde_json::to_string(&self)
            .unwrap()
            .trim_matches('"')
            .to_string()
    }

    /// Deserialize from a printable format.
    pub fn deserialize(input: &str) -> Self {
        if input.is_empty() || input.len() < 12 {
            return Id::default();
        }

        if is_numeric(input) {
            Id::Legacy(input.parse().unwrap())
        } else {
            let uuid = Uuid::from_u128(match decode(input) {
                Ok(x) => x,
                Err(_) => return Id::default(),
            });

            Id::Next(tritools::id::Id(uuid))
        }
    }
}

impl Serialize for Id {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Self::Next(x) => serializer.serialize_str(&x.printable()),
            Self::Legacy(x) => serializer.serialize_str(&x.to_string()),
        }
    }
}

struct IdVisitor;

fn is_numeric(haystack: &str) -> bool {
    for c in haystack.chars() {
        if !c.is_numeric() {
            return false;
        }
    }

    true
}

macro_rules! impl_number_visitor {
    ($n:ident, $t:ty) => {
        fn $n<E>(self, v: $t) -> Result<Self::Value, E>
        where
            E: serde::de::Error,
        {
            Ok(Id::Legacy(v as usize))
        }
    };
}

impl<'de> Visitor<'de> for IdVisitor {
    type Value = Id;

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        formatter.write_str("a string")
    }

    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Id::deserialize(&v))
    }

    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: serde::de::Error,
    {
        Ok(Id::deserialize(v))
    }

    impl_number_visitor!(visit_f32, f32);
    impl_number_visitor!(visit_i32, i32);
    impl_number_visitor!(visit_u32, u32);
    impl_number_visitor!(visit_i64, i64);
    impl_number_visitor!(visit_u64, u64);
    impl_number_visitor!(visit_i128, i128);
    impl_number_visitor!(visit_u128, u128);
}

impl<'de> Deserialize<'de> for Id {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(IdVisitor)
    }
}

impl Display for Id {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.printable())
    }
}

impl Default for Id {
    fn default() -> Self {
        Self::Legacy(0)
    }
}
