use chrono::{NaiveDate, Weekday};
use leptos::use_context;
use crate::locales::catalogues::get_dictionary;

mod catalogues;

#[derive(Debug, Clone)]
pub struct Locales(pub Vec<Option<String>>);

pub fn init_locales() {
    #[cfg(not(feature = "ssr"))]
    {
        use leptos::*;
        let loc = Locales(
            window()
                .navigator()
                .languages()
                .into_iter()
                .map(|val| val.as_string())
                .collect::<Vec<_>>(),
        );
        provide_context(loc);
    }

    #[cfg(feature = "ssr")]
    {
        use actix_web::HttpRequest;
        use leptos::provide_context;

        let req = use_context::<HttpRequest>();
        if let Some(r) = req {
            if r.query_string().contains("lang") {
                let languages = r.query_string()
                    .split("&")
                    .map(|qc| {
                        let mut it = qc.split("=").take(2); (it.next().unwrap_or(""), it.next().unwrap_or(""))
                    })
                    .filter(|l| l.0 == "lang")
                    .map(|l| l.1)
                    .collect::<Vec<_>>();
                if !languages.is_empty() {
                    provide_context(Locales(vec![Some(languages.get(0).unwrap().to_string())]));
                }
            } else if let Some(al) = r.head().headers.get("accept-language") {
                let loc = Locales(al.to_str().unwrap_or("").split(",").map(|l| Some(l.to_string())).collect());
                provide_context(loc);
            }
        }
    }
}

pub fn trl(phrase: &str) -> impl Fn() -> String {
    let mut translated = phrase;
    if let Some(dict) = get_dictionary() {
        if let Some(p) = dict.get(phrase.to_string().as_str()) {
            translated = *p;
        }
    }

    let out = translated.to_string();

    move || { out.clone() }
}

// ToDo better date formatting
pub fn loc_date(date: NaiveDate) -> impl Fn() -> String {
    let mut dt = date.format("%Y-%m-%d").to_string();
    let locs = use_context::<Locales>().unwrap_or(Locales(vec![])).0;
    for loc in locs {
        if let Some(key) = loc {
            if let Some(k) = key.split("-").collect::<Vec<_>>().get(0) {
                if *k != "en" {
                    dt = date.format("%d. %m. %Y").to_string();
                }
            }
        }
    }

    move || { dt.clone() }
}

pub fn show_day(day: &Weekday) -> impl Fn() -> String {
    match day {
        Weekday::Mon => { trl("Monday") }
        Weekday::Tue => { trl("Tuesday") }
        Weekday::Wed => { trl("Wednesday") }
        Weekday::Thu => { trl("Thursday") }
        Weekday::Fri => { trl("Friday") }
        Weekday::Sat => { trl("Saturday") }
        Weekday::Sun => { trl("Sunday") }
    }
}