# Rain:
#     - Light Green (Sct)
#     - Green (Rain)
#     - Dark Green (Heavy Rain)

# Snow:
#     - Faded White (transparent) - Light Snow
#     - White (Snow) - Snow

# Icy:
#     - Dark Pink

# Mix:
#     - Light Pink

# Severe:
#     - Red

# Fog:
#     - Yellow


# Layers:
#     - Basemap
#     - Travel Forecast (Modded)
#     - T'Storm forecast (Severe only)
#     - Cities
#     - Title bar overlay

from PIL import Image, ImageDraw, ImageFont
import requests
from gen_data import draw_shadow, draw_text_psd_style, draw_text_psd_style_shadow
from twc_icon_codes import engFcst
import numpy as np

from region_config import region_config


def black_to_transparent(img):
    # Convert Raster black to transparent
    img = img.convert("RGBA")
    img_data = img.getdata()

    newData = []
    for item in img_data:
        if item[0] == 0 and item[1] == 0 and item[2] == 0:
            newData.append((255, 255, 255, 0))
        else:
            # Opacity 90%
            newData.append((item[0], item[1], item[2], int(256 * 0.9)))

    img.putdata(newData)

    return img


def process_travel_frames():
    # # Download files
    # for filename in ["prod_travel_weather_8.png", "prod_thunderstorm_forecast_8.png"]:
    #     url = f"https://wxdata-us-central1.opntele.com/res/{filename}"
    #     # XXX: TODO: XXX: TODO: PASSWORD !!!!
    #     r = requests.get(url, allow_redirects=True, auth=("username", "password"))
    #     open(f"res/{filename}", "wb").write(r.content)

    # Basemap
    output = Image.open("data/static/slides/final2.png")

    # Travel
    # travel_image = Image.open("res/prod_travel_weather_8.png").convert("RGBA")
    # travel_image = black_to_transparent(travel_image)
    # output = Image.alpha_composite(output, travel_image)

    # T'Storm
    # ts_image = Image.open("res/prod_thunderstorm_forecast_8.png").convert("RGBA")
    # ts_image = black_to_transparent(ts_image)
    # output = Image.alpha_composite(output, ts_image)

    # Outline
    outline_image = Image.open("data/static/slides/outlines.png")
    output = Image.alpha_composite(output, outline_image)

    # # Save Supercut
    # output.save("output.png")


    # # WaterBG
    water_bg_image = Image.open("data/static/slides/water_bg_640.png")

    # # Title bar Overlay
    title_bar_overlay = Image.open("data/static/slides/travel_overlay.png")

    # Fonts
    header_font = ImageFont.truetype("data/static/slides/Interstate-Regular.ttf", 26)
    font_label = ImageFont.truetype("data/static/slides/Interstate-BoldUncondensed.ttf", 16)
    font_temp = ImageFont.truetype("data/static/slides/AkzidenzGroteskBE-Bold.otf", 24)

    # Get Data
    all_coop_ids = []

    for output_config_entry in region_config:
        for city in output_config_entry["cities"]:
            all_coop_ids.append(city["coopid"])

    res = requests.post("https://wxdata-us-central1.opntele.com/twc_star/satlf_data", json={"coop_ids": all_coop_ids})
    res.raise_for_status()
    all_data = res.json()


    # Do Regions
    print("Starting to create cuts for", "travel")
    for output_config_entry in region_config:
        # Crop the source image with the given coordinates
        cropped = output.crop(output_config_entry["crop"])

        # Resize the cropped image to 640x480
        cropped = cropped.resize((640, 480), Image.Resampling.LANCZOS)

        # Paste the cropped image into the output image
        img = Image.alpha_composite(water_bg_image, cropped)

        draw = ImageDraw.Draw(img)

        # Cities
        for city in output_config_entry["cities"]:
            city_name = city["name"]

            data = all_data[f"{city['coopid']}"]
            hi_temp = data['high_temp']
            lo_temp = data['low_temp']
            icon_code = data['icon_code']

            # Positions
            icon_x = city["icon_x"]
            icon_y = city["icon_y"]
            city_label_x = icon_x - 28
            city_label_y = icon_y + 55
            
            hi_temp_label_x = icon_x - 52
            hi_temp_label_y = icon_y + 10
            lo_temp_label_x = icon_x - 52
            lo_temp_label_y = icon_y + 33

            # City name
            lines = city_name.split("\n")
            for i, line in enumerate(lines):
                # Calculate the width of the text
                _, _, text_w, _ = draw.textbbox(
                    (0, 0), line, font=font_label
                )
                # Find the offset to center the text
                offset = (72 - text_w) / 2

                # TEST BOX
                # draw.rectangle(((city_label_x, city_label_y), (city_label_x+72, city_label_y+10)), outline="red")

                draw_text_psd_style_shadow(
                    draw,
                    (city_label_x + offset, city_label_y + (i * 16)),
                    line,
                    font_label,
                    fill=(255, 251, 128),
                    tracking=20,
                    shadowwidth=2,
                    shadowheight=2
                )
                
            # hi_temp
            _, _, temp_text_w, _ = draw.textbbox(
                (0, 0), hi_temp, font=font_temp
            )
            # TEST BOX
            # draw.rectangle(((temp_text_anchor_x, temp_text_anchor_y), (temp_text_anchor_x+72, temp_text_anchor_y+10)), outline="red")
            draw_text_psd_style_shadow(
                draw, 
                (hi_temp_label_x + ((72 - temp_text_w) / 2), hi_temp_label_y),
                hi_temp,
                font_temp,
                fill=(255, 255, 255),
                shadowcolor=(0, 0, 0),
                leading=21,
                shadowwidth=2,
                shadowheight=2
            )

            # draw = draw_shadow(
            #     draw,
            #     hi_temp_label_x + ((72 - temp_text_w) / 2),
            #     hi_temp_label_y,
            #     hi_temp,
            #     font_temp,
            #     # (223, 248, 178),
            #     # (218, 227, 145),
            #     (255, 255, 255),
            #     (0, 0, 0),
            #     shadowwidth=1,
            # )

            # lo_temp
            _, _, temp_text_w, _ = draw.textbbox(
                (0, 0), lo_temp, font=font_temp
            )
            # TEST BOX
            # draw.rectangle(((temp_text_anchor_x, temp_text_anchor_y), (temp_text_anchor_x+72, temp_text_anchor_y+10)), outline="red")
            draw_text_psd_style_shadow(
                draw, 
                (lo_temp_label_x + ((72 - temp_text_w) / 2), lo_temp_label_y),
                lo_temp,
                font_temp,
                fill=(255, 255, 255),
                shadowcolor=(0, 0, 0),
                leading=21,
                shadowwidth=2,
                shadowheight=2
            )
            # draw = draw_shadow(
            #     draw,
            #     lo_temp_label_x + ((72 - temp_text_w) / 2),
            #     lo_temp_label_y,
            #     lo_temp,
            #     font_temp,
            #     # (223, 248, 178),
            #     # (218, 227, 145),
            #     (255, 255, 255),
            #     (0, 0, 0),
            #     shadowwidth=1,
            # )

            # Icon
            icon = engFcst[icon_code]
            iconFile = icon.iconFile
            icon_image = Image.open(f"data/static/slides/large/{iconFile}.png")
            icon_width = 57
            icon_height = 56
            icon_image = icon_image.resize((icon_width, icon_height))
            # Paste the icon
            # output_image.paste(icon_image, (icon_anchor_x, icon_anchor_y), icon_image)
            img.alpha_composite(icon_image, (icon_x, icon_y))

            # Add AM or PM if needed, based on the beginning of the icon file
            modifier_image = None
            if iconFile.startswith("AM") or "AM" in iconFile:
                modifier_image = Image.open("data/static/slides/am_overlay.png")
            elif iconFile.startswith("PM") or "PM" in iconFile:
                modifier_image = Image.open("data/static/slides/pm_overlay.png")

            if modifier_image:
                modifier_image = modifier_image.resize((icon_width, icon_height))
                img.alpha_composite(
                    modifier_image, (icon_x, icon_y)
                )

        # Add overlay
        img = Image.alpha_composite(img, title_bar_overlay)

        # Add text
        draw = ImageDraw.Draw(img)
        draw_text_psd_style(
            draw, (70, 42), data['header_label'], header_font, fill=(255, 255, 255), tracking=40,
        )

        # Save the output image
        outname = output_config_entry["name"]
        img.save(f"temp/trv_{outname}.png")
        print("Done saving", outname)
