use std::fmt;
use std::fmt::Formatter;

use serde::{Deserialize, Serialize};

#[repr(i64)]
#[derive(Deserialize, Serialize, Copy, Clone, PartialEq, sqlx::Type)]
pub enum Unit {
    Kg,
    G,
    L,
    Ml,
    Stk,
}

impl Unit {
    pub const VEC: &'static [Unit] = &[Unit::Kg, Unit::G, Unit::L, Unit::Ml, Unit::Stk];

    pub fn position(&self) -> usize {
        Unit::VEC.iter().position(|r| *r == *self).unwrap()
    }

    // TODO: Convert function for units if possible/needed

}

fn to_string(unit: Unit, f: &mut Formatter) -> fmt::Result {
    match unit {
        Unit::Kg => write!(f, "Kilogramm"),
        Unit::G => write!(f, "Gramm"),
        Unit::L => write!(f, "Liter"),
        Unit::Ml => write!(f, "Milliliter"),
        Unit::Stk => write!(f, "Stück"),
    }
}

impl fmt::Debug for Unit {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        to_string(*self, f)
    }
}

impl fmt::Display for Unit {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        to_string(*self, f)
    }
}
