use i18n_embed::fluent::{FluentLanguageLoader, fluent_language_loader};
use i18n_embed::unic_langid::LanguageIdentifier;
use i18n_embed::{DefaultLocalizer, LanguageLoader, LanguageRequester, Localizer};
use rust_embed::RustEmbed;
use std::str::FromStr;
use std::sync::LazyLock;

#[derive(RustEmbed)]
#[folder = "i18n/"]
struct Localizations;

pub static LANGUAGE_LOADER: LazyLock<FluentLanguageLoader> = LazyLock::new(|| {
    let loader: FluentLanguageLoader = fluent_language_loader!();
    loader
        .load_fallback_language(&Localizations)
        .expect("Error while loading fallback language");
    loader
});

#[macro_export]
macro_rules! fl {
    ($message_id:literal) => {{
        i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id)
    }};

    ($message_id:literal, $($args:expr),*) => {{
        i18n_embed_fl::fl!($crate::localize::LANGUAGE_LOADER, $message_id, $($args),*)
    }};
}

pub fn localizer() -> Box<dyn Localizer> {
    Box::from(DefaultLocalizer::new(&*LANGUAGE_LOADER, &Localizations))
}

pub fn localize() {
    let localizer = localizer();
    let requested = i18n_embed::DesktopLanguageRequester::requested_languages();
    if let Err(e) = localizer.select(&requested) {
        eprintln!("i18n error: {e}");
    }
}

pub fn set_locale(locale: &str) {
    unsafe {
        std::env::set_var("LANG", locale);
    }

    if let Ok(lang_id) = LanguageIdentifier::from_str(locale) {
        let loc = localizer();
        let mut lang_requester = i18n_embed::DesktopLanguageRequester::new();
        _ = lang_requester.set_language_override(Some(lang_id));
        if let Err(e) = loc.select(&lang_requester.requested_languages()) {
            eprintln!("i18n error: {e}");
        }
    }
}
