import datetime

from markupsafe import Markup

from gallery.sketch.weather.model import (
    Cloudness,
    Precipitation,
    Sky,
    WindDirection,
    WindDirectionDeg,
)
from gallery.util import root_path


def wind_direction_icon(wind_direction_deg: float) -> str:
    wind_direction = WindDirectionDeg(wind_direction_deg).direction
    if wind_direction == WindDirection.CALM:
        return "wind-calm"
    else:
        return f"wind-from-{wind_direction.name.lower()}"


def cloudness_icon(sky: Sky, date: datetime.datetime, period: str) -> list[str]:
    day = (3 < date.hour < 22) if period == "day" else True
    day_prefix = "day" if day else "night-alt"
    main_icon = ""
    if sky.thunder:
        main_icon = {
            Precipitation.NO: "lightning",
            Precipitation.SMALL_RAIN: "storm-showers",
            Precipitation.RAIN: "thunderstorm",
            Precipitation.HEAVY_RAIN: "thunderstorm",
            Precipitation.SHOWER: "thunderstorm",
            Precipitation.SNOW: "storm-showers",
            Precipitation.HEAVY_SNOW: "storm-showers",
        }[sky.precipitation]
        if sky.cloudness == Cloudness.PARTLY_CLOUDY:
            main_icon = f"{day_prefix}-{main_icon}"
    elif sky.precipitation == Precipitation.NO:
        main_icon = {
            Cloudness.CLEAR: "day-sunny" if day else "night-clear",
            Cloudness.PARTLY_CLOUDY: f"{day_prefix}-cloudy",
            Cloudness.CLOUDY: "cloud",
            Cloudness.MAINLY_CLOUDY: "cloudy",
        }[sky.cloudness]
    else:
        main_icon = {
            Precipitation.SMALL_RAIN: "showers",
            Precipitation.RAIN: "rain-mix",
            Precipitation.HEAVY_RAIN: "rain",
            Precipitation.SHOWER: "rain",
            Precipitation.SNOW: "snow",
            Precipitation.HEAVY_SNOW: "snow",
            Precipitation.HAIL: "hail",
        }[sky.precipitation]
        if sky.cloudness == Cloudness.PARTLY_CLOUDY:
            main_icon = f"{day_prefix}-{main_icon}"
    icons = [main_icon]
    return icons


class WeatherIconBundle:
    def __init__(self):
        self._icon_path = root_path / "static/dist/weather-icons/icons"
        self._cache = {}

    def _load_icon(self, icon: str) -> Markup:
        icon_file = self._icon_path / f"wi-{icon}.svg"
        return Markup(icon_file.read_text())

    def get(self, icon: str) -> Markup:
        if icon not in self._cache:
            self._cache[icon] = self._load_icon(icon)
        return self._cache[icon]


WEATHER_ICON_BUNDLE = WeatherIconBundle()


def weather_icon_svg(icon: str) -> Markup:
    return WEATHER_ICON_BUNDLE.get(icon)
