//! An ISO 4217 currency code.

#[cfg(test)]
pub(crate) mod test;

mod data;

use std::fmt;

#[doc(inline)]
pub use data::Code;

use crate::{
    from_warning_all, json,
    warning::{self, GatherWarnings as _},
    IntoCaveat as _, Verdict,
};

/// The warnings that can happen when parsing or linting a currency code.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Warning {
    /// The currency field does not require char escape codes.
    ContainsEscapeCodes,

    /// The field at the path could not be decoded.
    Decode(json::decode::Warning),

    /// The `country` is not a valid `ISO 3166-1` country code because it's not uppercase.
    PreferUpperCase,

    /// The `currency` is not a valid `ISO 4217` currency code.
    InvalidCode,

    /// The JSON value given is not a string.
    InvalidType { type_found: json::ValueKind },

    /// The `currency` is not a valid `ISO 4217` currency code: it should be 3 chars.
    InvalidLength,

    /// The `currency` is not a valid `ISO 4217` currency code because it's a test code.
    InvalidCodeXTS,

    /// The `currency` is not a valid `ISO 4217` currency code because it's a code for `no-currency`.
    InvalidCodeXXX,
}

impl Warning {
    fn invalid_type(elem: &json::Element<'_>) -> Self {
        Self::InvalidType {
            type_found: elem.value().kind(),
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ContainsEscapeCodes => write!(
                f,
                "The currency-code contains escape-codes but it does not need them.",
            ),
            Self::Decode(warning) => fmt::Display::fmt(warning, f),
            Self::PreferUpperCase => write!(
                f,
                "The currency-code follows the ISO 4217 standard which states: the chars should be uppercase.",
            ),
            Self::InvalidCode => {
                write!(f, "The currency-code is not a valid ISO 4217 code.")
            }
            Self::InvalidType { .. } => write!(f, "The currency-code should be a string."),
            Self::InvalidLength => write!(f, "The currency-code follows the ISO 4217 standard which states: the code should be three chars."),
            Self::InvalidCodeXTS => write!(
                f,
                "The currency-code is `XTS`. This is a code for testing only",
            ),
            Self::InvalidCodeXXX => write!(
                f,
                "The currency-code is `XXX`. This means there is no currency",
            ),
        }
    }
}

impl crate::Warning for Warning {
    fn id(&self) -> warning::Id {
        match self {
            Self::ContainsEscapeCodes => warning::Id::from_static("contains_escape_codes"),
            Self::Decode(kind) => kind.id(),
            Self::PreferUpperCase => warning::Id::from_static("prefer_upper_case"),
            Self::InvalidCode => warning::Id::from_static("invalid_code"),
            Self::InvalidType { type_found } => {
                warning::Id::from_string(format!("invalid_type({type_found})"))
            }
            Self::InvalidLength => warning::Id::from_static("invalid_length"),
            Self::InvalidCodeXTS => warning::Id::from_static("invalid_code_xts"),
            Self::InvalidCodeXXX => warning::Id::from_static("invalid_code_xxx"),
        }
    }
}

from_warning_all!(json::decode::Warning => Warning::Decode);

impl json::FromJson<'_> for Code {
    type Warning = Warning;

    fn from_json(elem: &json::Element<'_>) -> Verdict<Self, Self::Warning> {
        let mut warnings = warning::Set::new();
        let value = elem.as_value();

        let Some(s) = value.to_raw_str() else {
            return warnings.bail(elem, Warning::invalid_type(elem));
        };

        let pending_str = s.has_escapes(elem).gather_warnings_into(&mut warnings);

        let s = match pending_str {
            json::PendingStr::NoEscapes(s) => s,
            json::PendingStr::HasEscapes(_) => {
                return warnings.bail(elem, Warning::ContainsEscapeCodes);
            }
        };

        let bytes = s.as_bytes();

        // ISO 4217 is expected to be 3 chars enclosed in quotes.
        let [a, b, c] = bytes else {
            return warnings.bail(elem, Warning::InvalidLength);
        };

        let triplet: [u8; 3] = [
            a.to_ascii_uppercase(),
            b.to_ascii_uppercase(),
            c.to_ascii_uppercase(),
        ];

        if triplet != bytes {
            warnings.insert(elem, Warning::PreferUpperCase);
        }

        let Some(code) = Code::from_alpha_3(triplet) else {
            return warnings.bail(elem, Warning::InvalidCode);
        };

        if matches!(code, Code::Xts) {
            warnings.insert(elem, Warning::InvalidCodeXTS);
        } else if matches!(code, Code::Xxx) {
            warnings.insert(elem, Warning::InvalidCodeXXX);
        }

        Ok(code.into_caveat(warnings))
    }
}

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

/// Macro to specify a list of valid ISO 4217 alpha-3 currency codes.
macro_rules! currency_codes {
    [$(($name:ident, $alpha3:literal, $symbol:literal)),*] => {
        /// An ISO 4217 currency code.
        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash,  PartialOrd, Ord)]
        pub enum Code {
            $($name),*
        }

        impl Code {
            /// Try creating a `Code` from three upper ASCII bytes.
            pub(super) const fn from_alpha_3(code: [u8; 3]) -> Option<Self> {
                match &code {
                    $($alpha3 => Some(Self::$name),)*
                    _ => None
                }
            }

            /// Return enum as three byte uppercase &str.
            pub fn into_str(self) -> &'static str {
                let bytes = match self {
                    $(Self::$name => $alpha3),*
                };
                std::str::from_utf8(bytes).expect("The currency code bytes are known to be valid UTF8 as they are embedded into the binary")
            }

            /// Return a str symbol of the [Code].
            pub fn into_symbol(self) -> &'static str {
                match self {
                    $(Self::$name => $symbol),*
                }
            }
        }
    };
}

pub(crate) use currency_codes;
