import datetime
import statistics

from .model import Cloudness, Precipitation, Sky, WeatherValue, WindDirectionDeg


def build_weather_value(date: datetime.datetime) -> WeatherValue:
    return WeatherValue(
        date=date,
        sky=Sky(
            cloudness=Cloudness.CLEAR,
            precipitation=Precipitation.NO,
            thunder=False,
            fog=False,
        ),
        temperature=[],
        wind_speed=0,
        wind_gust=0,
        wind_direction=WindDirectionDeg(-1),
        precipitation=0,
        pressure=[],
        humidity=0,
    )


def merge_weather_values(date: datetime.datetime, values: list[WeatherValue]) -> WeatherValue:
    result = build_weather_value(date)
    temperatures = []
    pressures = []
    humidities = []
    wind_speeds = []
    wind_gusts = []
    wind_directions = []
    cloudnesses = []
    precipitations = []
    precipitation = 0
    for value in values:
        temperatures += value.temperature
        pressures += value.pressure
        humidities.append(value.humidity)
        wind_speeds.append(value.wind_speed)
        wind_gusts.append(value.wind_gust)
        wind_directions.append(value.wind_direction)
        cloudnesses.append(value.sky.cloudness)
        precipitations.append(value.sky.precipitation)
        precipitation += value.precipitation
    result.temperature = [max(temperatures), min(temperatures)]
    result.pressure = [max(pressures), min(pressures)]
    result.humidity = round(statistics.mean(humidities))
    result.wind_speed = round(statistics.mean(wind_speeds))
    result.wind_gust = round(statistics.mean(wind_gusts))
    result.wind_direction = statistics.mean(wind_directions)
    # TODO: merge cloudnesses
    for item in cloudnesses:
        if item != Cloudness.CLEAR:
            result.sky.cloudness = item
    # TODO: merge precipitations
    for item in precipitations:
        if item != Precipitation.NO:
            result.sky.precipitation = item
    result.precipitation = precipitation
    return result
