from pyweb import pydom
from pyscript import document
import locale

locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')

from client import MeteoFranceClient
from const import METEOFRANCE_API_URL
from datetime import date
import urllib3
import js

JR_SEM = [
    "lundi",
    "mardi",
    "mercredi",
    "jeudi",
    "vendredi",
    "samedi",
    "dimanche",
]

MS_ANN = [
    "janvier",
    u"février",
    "mars",
    "avril",
    "mai",
    "juin",
    "juillet",
    u"août",
    "septembre",
    "octobre",
    "novembre",
    u"décembre",
]

# dico normalisé jc versus descriptif MF :
DICO_PLUIE = {
    "Temps sec": "pluie0",
    "Pluie faible": "pluie1",
    "Pluie modèrée": "pluie2",
    "Pluie forte": "pluie3",
}	
	
def show_page():  
	xinput = pydom["#page_princip"][0] 
	xinput._js.style.display="block"
		
def hide_loader():  
	xinput = pydom["#loader-container"][0] 
	xinput._js.style.display="none"	
	show_page()	

def q(selector, root=document):
    return root.querySelector(selector)


def date_vers_lit(d: date):
    ic = d.isocalendar()
    it = d.timetuple()
    return f"{JR_SEM[d.isocalendar()[2] - 1]}" + " " + d.strftime(
        "%d") + " " + f"{MS_ANN[d.timetuple()[1] - 1]}" 
        
        #return f"{JR_SEM[d.isocalendar()[2] - 1]}" + " " + d.strftime(
        #"%d") + " " + f"{MS_ANN[d.timetuple()[1] - 1]}" + " " + d.strftime("%Y")


def date_vers_jour_clair(d: date):
    ic = d.isocalendar()
    return f"{JR_SEM[d.isocalendar()[2] - 1]}"


def add_previ(descript, tps_previ, jr_nt, previ_icon):
    # create previ
    previ_id = f"previ-{len(previs)}"
    previ = {
        "id": previ_id,
        "previ_heure": tps_previ,
        "content": descript,
        "j_n": jr_nt,
        "pr_icon": previ_icon,
    }

    previs.append(previ)

    previ_html = previ_template.clone()
    previ_html.id = previ_id

    previ_html_content = previ_html.find("p.p_p1")[0]
    previ_html_content._js.textContent = previ["content"]

    previ_html_content = previ_html.find("p.p_p2")[0]
    previ_html_content._js.textContent = previ["previ_heure"]

    txt1 = previ["pr_icon"]
    previ_html_content = previ_html.find("img")[0]
    previ_html_content._js.srcset = txt1
    previ_list.append(previ_html)


def add_previ10(nijour, flag_jour, previ_date, t_value, vent_debout, humidity, weather_desc, clouds, rain_1h,
                weather_icon, snow_icon,
                snow_limit, snow_1h, wind_speed, wind_dir, wind_icon, gust, rise, sety, inewjour, isnow, isnowfall):
    # create previ10
    previ10_id = f"previ10-{len(previs10)}"
    previ10 = {
        "id": previ10_id,
        "date": previ_date,
        "t_value": t_value,
        "vent_debout": vent_debout,
        "humidity": humidity,
        "weather_desc": weather_desc,
        "clouds": clouds,
        "rain_1h": rain_1h,
        "weather_icon": weather_icon,
        "snow_icon": snow_icon,
        "snow_limit": snow_limit,
        "snow_1h": snow_1h,
        "wind_speed": wind_speed,
        "wind_dir": wind_dir,
        "wind_icon": wind_icon,
        "gust": gust,
    }
    previs10.append(previ10)


def view_previs(xprevi: object, deb_range , fin_range):
    previ10 = xprevi
    k = 0
    print(" dans view_previs : ", deb_range, " fin de range : ", fin_range)
    for k in range(deb_range, fin_range):
        print(" num previ : ", k)
        if flag_jour:
            print("page clonée")
        # print("previs teta :     ", previ10[2:3])
        previ10_html = previ10_template.clone()
        previ10_html.id = previ10[k]["id"]
        print("id previs : ", previ10[k]["id"])

        x = date_vers_lit(previ10[k]["date"])
        y = previ10[k]["date"].strftime('%Hh')
        iy = int(previ10[k]["date"].strftime('%H'))
        ijour = int(previ10[k]["date"].strftime('%d'))
        jour_clair = date_vers_jour_clair(previ10[k]["date"])

        previ10_html_content = previ10_html.find("#jr_nt")[0]

        if inewjour:
            previ10_html_content._js.textContent = f"{x}  {y}"
        else:
            previ10_html_content._js.textContent = f"{jour_clair} {y}"

        previ10_html_content = previ10_html.find("#div_card")[0]
        if iy >= irise and iy < isety:
            previ10_html_content._js.style = "background-color : #cceeff; width: 20rem;"

        else:
            previ10_html_content._js.style = "background-color : #f1f1f1; width: 20rem;"
        # cyan cceeff
        # gris f1f1f1

        previ10_html_content = previ10_html.find("#t_value")[0]
        x = previ10[k]["t_value"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#p_vent_debout")[0]
        x = previ10[k]["vent_debout"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#p_humidity")[0]
        x = previ10[k]["humidity"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#p_weather_desc")[0]
        previ10_html_content._js.textContent = previ10[k]["weather_desc"]

        previ10_html_content = previ10_html.find("#p_clouds")[0]
        x = previ10[k]["clouds"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#p_rain_1h")[0]
        x = previ10[k]["rain_1h"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#img_weather_icon")[0]
        txt1 = previ10[k]["weather_icon"]
        # print("source image : ", txt1  )
        previ10_html_content._js.srcset = txt1

        if isnow:
            previ10_html_content = previ10_html.find("#flag_neige")[0]
            previ10_html_content._js.srcset = "Neige"

            previ10_html_content = previ10_html.find("#p_snow_limit")[0]
            x = previ10[k]["snow_limit"]
            previ10_html_content._js.textContent = x

            if isnowfall:
                previ10_html_content = previ10_html.find("#img_snow_icon")[0]
                txt1 = previ10[k]["snow_limit"]
                previ10_html_content._js.srcset = txt1

                previ10_html_content = previ10_html.find("#p_snow_1h")[0]
                x = previ10[k]["snow_1h"]
                previ10_html_content._js.textContent = x
            else:
                previ10_html_content = previ10_html.find("#img_snow_icon")[0]
                txt1 = previ10[k]["snow_icon"]
                previ10_html_content._js.srcset = ""

                previ10_html_content = previ10_html.find("#p_snow_1h")[0]
                x = previ10[k]["snow_1h"]
                previ10_html_content._js.textContent = ""

                previ10_html_content = previ10_html.find("#ng03")[0]
                previ10_html_content._js.textContent = ""

                previ10_html_content = previ10_html.find("#ng04")[0]
                previ10_html_content._js.textContent = ""
        else:
            previ10_html_content = previ10_html.find("#flag_neige")[0]
            previ10_html_content._js.srcset = ""

            previ10_html_content = previ10_html.find("#img_snow_icon")[0]
            txt1 = previ10[k]["snow_icon"]
            previ10_html_content._js.srcset = ""

            previ10_html_content = previ10_html.find("#p_snow_limit")[0]
            x = previ10[k]["snow_limit"]
            previ10_html_content._js.textContent = ""

            previ10_html_content = previ10_html.find("#p_snow_1h")[0]
            x = previ10[k]["snow_1h"]
            previ10_html_content._js.textContent = ""

            previ10_html_content = previ10_html.find("#ng01")[0]
            previ10_html_content._js.textContent = ""

            previ10_html_content = previ10_html.find("#ng02")[0]
            previ10_html_content._js.textContent = ""

            previ10_html_content = previ10_html.find("#ng03")[0]
            previ10_html_content._js.textContent = ""

            previ10_html_content = previ10_html.find("#ng04")[0]
            previ10_html_content._js.textContent = ""

        previ10_html_content = previ10_html.find("#p_wind_speed")[0]
        x = previ10[k]["wind_speed"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#p_gust")[0]
        x = previ10[k]["gust"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#p_wind_dir")[0]
        x = previ10[k]["wind_dir"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#img_wind_icon")[0]
        x = previ10[k]["wind_icon"]
        previ10_html_content._js.textContent = x

        previ10_html_content = previ10_html.find("#img_wind_icon")[0]
        txt1 = previ10[k]["wind_icon"]
        previ10_html_content._js.srcset = txt1

        previ10_list.append(previ10_html)




def j_n(dt, d_sun_rise, d_sun_set):
    if dt < d_sun_rise and dt > d_sun_set:
        return 0
    else:
        return 1


if not js.localStorage.getItem('mem_place'):
    js.localStorage.setItem('mem_place', "Saint Martin de Caralp")
else:
    xhtml = pydom["#place_enreg"][0]
    xhtml.html=js.localStorage.getItem('mem_place')
    
xstr=js.localStorage.getItem('mem_place')
    
previ_template = pydom.Element(q("#previ-template").content.querySelector(".previ"))
previ_list = pydom["#list-previ-container"][0]
previs = []

previ10_template = pydom.Element(q("#previ10-template").content.querySelector(".previ10"))
previ10_list = pydom["#list-previ10-container"][0]

previs10 = []

urllib3.disable_warnings()

client = MeteoFranceClient()

places = client.search_places(xstr)
obs = client.get_observation_for_place(places[0])
fcast = client.get_forecast_for_place(places[0])
rain = client.get_rain(places[0].latitude, places[0].longitude, language='fr')
pict_of_day = client.get_picture_of_the_day()

pydom["div#obsv_date"].html = date_vers_lit(obs.time_as_datetime)  # .strftime('%a %d %B %Y, %H:%M ')
pydom["div#obsv_txt"].html = obs.weather_description

txt_obs_icon = obs.weather_icon
txt_fich_obs_icon = f"/squelettes-dist/mto/assets/icones/{txt_obs_icon}.png"

xbox = pydom.Element(q("#img3"))  # .content.querySelector(".previ"))
xbox._js.srcset = txt_fich_obs_icon

pydom["div#obsv_teta"].html = f"Température :{obs.temperature} °C"
pydom["div#obsv_wd_speed"].html = f"Vent : {obs.wind_speed} km/h  Direction : {obs.wind_direction}"
pydom["div#obsv_wd_icon"].html = obs.wind_icon

ybox = pydom.Element(q("#img4"))
xtxt = f"/squelettes-dist/mto/assets/icones/vents/{obs.wind_icon}.png"
ybox._js.srcset = xtxt

# prévision journalière et variables jour/nuit
to_d_fcast = fcast.today_forecast
h_sun_rise = rain.timestamp_to_locale_time(to_d_fcast.get('sun').get('rise')).strftime('%a %d %B %Y, %H:%M ')
h_sun_set = rain.timestamp_to_locale_time(to_d_fcast.get('sun').get('set')).strftime('%a %d %B %Y, %H:%M ')

dt = rain.timestamp_to_locale_time(to_d_fcast.get('dt'))

# print(" Prévisions  établies à :  ", )
pydom["div#previ_date"].html = date_vers_lit(dt) + dt.strftime(' %H:%M ')

# print("     Températures. mini : ", (, " maxi : ",)
pydom[
    "div#previ_teta_min_max"].html = f"Température (°C)  minimale :  {to_d_fcast.get('T').get('min')}  maximale :  {to_d_fcast.get('T').get('max')}"

# print("     Humidité. mini : ", (, " maxi : ",
pydom[
    "div#previ_hr_min_max"].html = f"Humidité (%)  minimale :  {to_d_fcast.get('humidity').get('min')} maximale  :  {to_d_fcast.get('humidity').get('max')}"

# print("     Précipitations : ", () print("     UV : ", )
pydom[
    "div#previ_precip_24_uv"].html = f"Précipitations sur 24h  :  {to_d_fcast.get('precipitation').get('24h')} mm.  Indice UV :  {to_d_fcast.get('uv')}"

# print("     Icone  : ", , " descriptif : ",to_d_fcast.get('weather12H').get('desc'))
txt_icon = to_d_fcast.get('weather12H').get('icon')

# print(" Lever de soleil : ", , "coucher : "
rise = rain.timestamp_to_locale_time(to_d_fcast.get('sun').get('rise')).strftime(' %H:%M ')
irise = int(rain.timestamp_to_locale_time(to_d_fcast.get('sun').get('rise')).strftime('%H'))
sety = rain.timestamp_to_locale_time(to_d_fcast.get('sun').get('set')).strftime(' %H:%M ')
isety = int(rain.timestamp_to_locale_time(to_d_fcast.get('sun').get('set')).strftime('%H'))
xx = "  "
pydom["div#previ_hr_rise_set"].html = f"Ephéméride soleil.  {xx:4}         Lever :  {rise:4}   coucher :   {sety}"

# pict of day url de l'image et description
pydom["div#pict_url"].html = pict_of_day.image_url
pydom["div#pict_desc"].html = pict_of_day.description

# pluies dans l'heure à venir
next_rain = rain.next_rain_date_locale()
xstr_icon = ""
i = 0
x = ""

for tbl in rain.forecast:
    date = rain.timestamp_to_locale_time(tbl.get('dt'))
    if i == 0:
        xdate = date_vers_lit(date) + date.strftime(' %H:%M ')
        i = 1
    else:
        xdate = date.strftime(' %H:%M ')
    xj_n = j_n(xdate, h_sun_rise, h_sun_set)
    y = tbl.get('desc')
    try:
        x = DICO_PLUIE[y]
    except KeyError:
        x = 'quest'
    txt_fich_obs_icon = f"/squelettes-dist/mto/assets/icones/icones_norm_jc/{x}.png"
    add_previ(tbl.get('desc'), xdate, xj_n, txt_fich_obs_icon)

ijour = 0
isnow = 0
isnowfall = 0

delta0 = 3600
delta1 = 0
d_before = 0
d_stage = 0
xjour = ""
xjour0 = ""
flag_jour = 0
nijour = 0

ndelta3600 = 0
ndelta10800 = 0
ndelta21600 = 0



for frcst in fcast.forecast:
    flag_jour = 0
    date = frcst.get('dt')
    ydate = fcast.timestamp_to_locale_time(date)
    xdate = fcast.timestamp_to_locale_time(date).strftime('%a %d %B %Y, %H:%M ')

    xjour = fcast.timestamp_to_locale_time(date).strftime('%a')
    delta1 = delta0
    d_before = d_stage
    date = frcst.get('dt')
    d_stage = date
    if d_before == 0:
        delta0 = 3600
        ndelta3600 = 0
        ndelta10800 = 0
        ndelta21600 = 0
    else:
        delta0 = d_stage - d_before
        if delta0 == 3600: ndelta3600 = ndelta3600 + int(3600 / delta0)
        if delta0 == 10800: ndelta10800 = ndelta10800 + int(10800 / (delta0))
        if delta0 == 21600: ndelta21600 = ndelta21600 + int(21600 / (delta0))

    if xjour != xjour0:
        xjour0 = xjour
        flag_jour = 1
        nijour = nijour + 1

    if delta1 != delta0:
        # print("on change de durée de prévi.")
        xjour = int(fcast.timestamp_to_locale_time(date).strftime('%d'))

    # flg pour détecter un nouveau jour
    if ijour != xjour:
        inewjour = 1
    else:
        inewjour = 0

    t_value = frcst.get('T').get('value')
    vent_debout = frcst.get('T').get('windchill')
    humidity = frcst.get('humidity')
    clouds = frcst.get('clouds')

    weather_desc = frcst.get('weather').get('desc')

    rain_1h = frcst.get('rain').get('1h')

    xsnow_limit = frcst.get('rain snow limit')

    xsnow_fall = frcst.get('snow').get("1h")

    snow_limit = 0
    snow_fall = 0

    snow_1h = frcst.get('snow').get('1h')
    snow_icon = f"/squelettes-dist/mto/assets/icones/icones_norm_jc/{x}.png"
    if xsnow_limit == "Non pertinent":
        snow_limit = 0
    else:
        snow_limit = int(snow_limit)

    if xsnow_fall == "None" or xsnow_fall == 0:
        snow_fall = 0
    else:
        snow_fall = int(snow_fall)

    if snow_limit > 0:
        isnow = 1
        if snow_fall > 0:
            isnowfall = 1
        else:
            isnowfall = 0
    else:
        isnow = 0
        isnowfall = 0
    # print(xdate,"   valeurs flags neige : isnow ", isnow, " isnowfall :", isnowfall	)
    weather_desc = frcst.get('weather').get('desc')
    weather_icon = f"/squelettes-dist/mto/assets/icones/{frcst.get('weather').get('icon')}.png"

    wind_dir = frcst.get('wind').get('direction')
    wind_speed = frcst.get('wind').get('speed')
    gust = frcst.get('wind').get('gust')
    wind_icon = f"/squelettes-dist/mto/assets/icones/vents/{frcst.get('wind').get('icon')}.png"

    ijour = add_previ10(nijour, flag_jour, ydate, t_value, vent_debout, humidity, weather_desc, clouds, rain_1h,
                        weather_icon, snow_icon, snow_limit, snow_1h, wind_speed, wind_dir, wind_icon, gust, irise,
                        isety, inewjour, isnow, isnowfall)

view_previs(previs10, 0, ndelta3600+2)
view_previs(previs10, ndelta3600+2, ndelta3600+ndelta10800+2)
view_previs(previs10, ndelta3600+ndelta10800+1, ndelta3600+ndelta10800+1+ndelta21600)
hide_loader()

