import St from "gi://St";

import Clutter from "gi://Clutter";

import GLib from "gi://GLib";

import Gio from "gi://Gio";

import Soup from "gi://Soup?version=3.0";

import { loadTranslations } from "./i18n/index.js";

import { SHADOW_DEFAULTS, shadowBoxShadowCss as _shadowBoxShadowCss, parseFontDescription as _parseFontDescription, cardStyleCss as _cardStyleCss, BORDER_DEFAULTS, OPACITY_DEFAULTS, deferUntilMapped as _deferUntilMapped } from "../../lib/widgetVisualKit.js";

import { createLayeredCard, applyLayeredCardStyle } from "../../lib/shell/cardLayers.js";

import {configJsonDefaults} from '../../lib/widgetConfigDefaults.js';
const FORECAST_URL = "https://api.open-meteo.com/v1/forecast";

const REFRESH_SECONDS = 15 * 60;

function _describeWeather(code, isDay) {
    const day = isDay !== 0;
    switch (code) {
      case 0:
        return {
            icon: day ? "weather-sun" : "weather-moon",
            condition: "Clear"
        };

      case 1:
        return {
            icon: day ? "weather-sun" : "weather-moon",
            condition: "Mainly Clear"
        };

      case 2:
        return {
            icon: day ? "weather-cloud-sun" : "weather-cloud-moon",
            condition: "Partly Cloudy"
        };

      case 3:
        return {
            icon: "weather-cloud",
            condition: "Overcast"
        };

      case 45:
      case 48:
        return {
            icon: "weather-fog",
            condition: "Fog"
        };

      case 51:
      case 53:
      case 55:
        return {
            icon: "weather-cloud-drizzle",
            condition: "Drizzle"
        };

      case 56:
      case 57:
        return {
            icon: "weather-cloud-sleet",
            condition: "Freezing Drizzle"
        };

      case 61:
      case 63:
      case 65:
        return {
            icon: "weather-cloud-rain",
            condition: "Rain"
        };

      case 66:
      case 67:
        return {
            icon: "weather-cloud-sleet",
            condition: "Freezing Rain"
        };

      case 71:
      case 73:
      case 75:
        return {
            icon: "weather-cloud-snow",
            condition: "Snow"
        };

      case 77:
        return {
            icon: "weather-cloud-snow-fine",
            condition: "Snow Grains"
        };

      case 80:
      case 81:
      case 82:
        return {
            icon: day ? "weather-cloud-sun-rain" : "weather-cloud-rain",
            condition: "Rain Showers"
        };

      case 85:
      case 86:
        return {
            icon: day ? "weather-cloud-sun-snow" : "weather-cloud-snow",
            condition: "Snow Showers"
        };

      case 95:
        return {
            icon: "weather-cloud-lightning",
            condition: "Storm"
        };

      case 96:
      case 99:
        return {
            icon: "weather-cloud-lightning-hail",
            condition: "Storm (Hail)"
        };

      default:
        return {
            icon: "weather-wind",
            condition: "Unknown"
        };
    }
}

export default class WeatherDarkWidget {
    constructor(api) {
        this._api = api;
        this._settings = api.settings;
        this._timeoutId = null;
        this._httpSession = null;
        this._coords = null;
        this._resolvedLocation = "";
        this._weather = null;
        this._iconDir = this._api.path?.me ? Gio.File.new_for_path(this._api.path.me).get_child("icons") : null;
        this._cacheDir = Gio.File.new_for_path(GLib.build_filenamev([ GLib.get_user_cache_dir(), "gnome-widget-center", "weather-dark" ]));
        this._translations = {};
    }
    _loadI18n() {
        if (!this._api.path?.me) return;
        loadTranslations(GLib.build_filenamev([ this._api.path.me, "i18n" ]), this._api.hostLanguage).then(translations => {
            this._translations = translations;
            this._render();
        }).catch(() => {});
    }
    onHostLanguageChanged() {
        this._loadI18n();
    }
    _trCondition(english) {
        const value = this._translations[`condition.${english}`];
        return typeof value === "string" && value.length > 0 ? value : english;
    }
    buildActor() {
        this._layers = createLayeredCard({
            contentStyleClass: "weather-dark-widget-root"
        });
        this._actor = this._layers.root;
        this._actor.x_align = Clutter.ActorAlign.START;
        this._actor.y_align = Clutter.ActorAlign.CENTER;
        this._content = new St.BoxLayout({
            vertical: false
        });
        this._layers.content.add_child(this._content);
        this._textBox = new St.BoxLayout({
            vertical: true,
            y_align: Clutter.ActorAlign.CENTER,
            x_expand: true,
            style: "spacing: 4px;"
        });
        this._tempLabel = new St.Label({
            style_class: "weather-dark-widget-temp"
        });
        this._conditionLabel = new St.Label({
            style_class: "weather-dark-widget-condition"
        });
        this._textBox.add_child(this._tempLabel);
        this._textBox.add_child(this._conditionLabel);
        this._iconBin = new St.Bin({
            style_class: "weather-dark-widget-icon",
            x_align: Clutter.ActorAlign.END,
            y_align: Clutter.ActorAlign.CENTER
        });
        this._content.add_child(this._textBox);
        this._content.add_child(this._iconBin);
        this._render();
        this._refresh();
        this._loadI18n();
        this._maybeAutoDetectLocation().catch(() => {});
        return this._actor;
    }
    enable() {
        this._timeoutId = GLib.timeout_add_seconds(GLib.PRIORITY_DEFAULT, REFRESH_SECONDS, () => {
            this._refresh();
            return GLib.SOURCE_CONTINUE;
        });
    }
    disable() {
        if (this._timeoutId !== null) {
            GLib.source_remove(this._timeoutId);
            this._timeoutId = null;
        }
        this._httpSession = null;
    }
    getDefaultSettings() {
        return {
            ...configJsonDefaults(import.meta.url),
            ...SHADOW_DEFAULTS,
            ...BORDER_DEFAULTS,
            ...OPACITY_DEFAULTS,
            locationAutoDetected: false,
        };
    }
    onSettingsChanged() {
        this._render();
        const location = this._settings.location ?? "";
        if (location !== this._resolvedLocation) this._refresh();
    }
    _getHttpSession() {
        if (!this._httpSession) this._httpSession = new Soup.Session;
        return this._httpSession;
    }
    async _fetchJson(url) {
        const session = this._getHttpSession();
        const message = Soup.Message.new("GET", url);
        if (!message) throw new Error(`invalid URL: ${url}`);
        const bytes = await session.send_and_read_async(message, GLib.PRIORITY_DEFAULT, null);
        if (message.get_status() !== Soup.Status.OK) throw new Error(`HTTP ${message.get_status()} for ${url}`);
        const text = new TextDecoder("utf-8").decode(bytes.get_data());
        return JSON.parse(text);
    }
    _parseLocation(value) {
        const match = /^(-?\d{1,2}(?:\.\d+)?)\s*,\s*(-?\d{1,3}(?:\.\d+)?)$/.exec(value.trim());
        if (!match) return null;
        const latitude = parseFloat(match[1]);
        const longitude = parseFloat(match[2]);
        if (latitude < -90 || latitude > 90 || longitude < -180 || longitude > 180) return null;
        return {
            latitude: latitude,
            longitude: longitude
        };
    }
    async _maybeAutoDetectLocation() {
        if (this._settings.locationAutoDetected) return;
        this._settings.locationAutoDetected = true;
        const location = this._settings.location ?? "";
        if (location && location !== "13.756331,100.501762") return;
        const coords = await this._fetchIpLocation();
        if (!coords) return;
        this._settings.location = `${coords.latitude},${coords.longitude}`;
        this._resolvedLocation = "";
        this._refresh();
    }
    async _fetchIpLocation() {
        const endpoints = [ {
            url: "http://ip-api.com/json/",
            parse: d => ({
                latitude: d.lat,
                longitude: d.lon
            })
        }, {
            url: "https://freeipapi.com/api/json",
            parse: d => ({
                latitude: d.latitude,
                longitude: d.longitude
            })
        }, {
            url: "https://ipwhois.io/json/",
            parse: d => ({
                latitude: d.latitude,
                longitude: d.longitude
            })
        } ];
        for (const {url: url, parse: parse} of endpoints) {
            try {
                const data = await this._fetchJson(url);
                const {latitude: latitude, longitude: longitude} = parse(data) ?? {};
                if (typeof latitude === "number" && typeof longitude === "number" && Number.isFinite(latitude) && Number.isFinite(longitude)) return {
                    latitude: latitude,
                    longitude: longitude
                };
            } catch (e) {
                this._api.logger.info(`weather-dark: ip geolocation via ${url} failed: ${e}`);
            }
        }
        return null;
    }
    async _refresh() {
        const location = this._settings.location ?? "13.756331,100.501762";
        try {
            const coords = this._parseLocation(location);
            if (!coords) throw new Error(`invalid "location" setting: "${location}" (expected "lat,lon")`);
            this._coords = coords;
            this._resolvedLocation = location;
            const {latitude: latitude, longitude: longitude} = coords;
            const url = `${FORECAST_URL}?latitude=${latitude}&longitude=${longitude}` + "&current=temperature_2m,weather_code,is_day&timezone=auto";
            const data = await this._fetchJson(url);
            const current = data.current ?? {};
            const tempC = current.temperature_2m;
            const {icon: icon, condition: condition} = _describeWeather(current.weather_code, current.is_day ?? 1);
            this._weather = {
                tempC: tempC,
                tempF: typeof tempC === "number" ? tempC * 9 / 5 + 32 : null,
                icon: icon,
                condition: condition
            };
        } catch (e) {
            this._api.logger.info(`weather-dark: refresh failed: ${e}`);
        }
        this._render();
    }
    _normalizeHexColor(value) {
        const fallback = "#f2b544";
        if (typeof value !== "string") return fallback;
        const trimmed = value.trim();
        if (/^#[0-9a-fA-F]{3}$|^#[0-9a-fA-F]{6}$|^#[0-9a-fA-F]{8}$/.test(trimmed)) return trimmed;
        const match = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(trimmed);
        if (match) {
            const toHex = n => Math.max(0, Math.min(255, parseInt(n, 10))).toString(16).padStart(2, "0");
            return `#${toHex(match[1])}${toHex(match[2])}${toHex(match[3])}`;
        }
        return fallback;
    }
    _getColoredIconFile(iconKey, colorHex) {
        if (!this._iconDir) return null;
        const srcFile = this._iconDir.get_child(`${iconKey}.svg`);
        if (!srcFile.query_exists(null)) return null;
        try {
            const safeColor = this._normalizeHexColor(colorHex);
            const cacheFile = this._cacheDir.get_child(`${iconKey}-${safeColor.replace("#", "")}.svg`);
            if (cacheFile.query_exists(null)) return cacheFile;
            const [, contents] = srcFile.load_contents(null);
            const svgText = new TextDecoder("utf-8").decode(contents);
            const recolored = svgText.replaceAll("#000000", safeColor);
            GLib.mkdir_with_parents(this._cacheDir.get_path(), 448);
            GLib.file_set_contents(cacheFile.get_path(), recolored);
            return cacheFile;
        } catch (e) {
            this._api.logger.info(`weather-dark: failed to recolor icon "${iconKey}": ${e}`);
            return srcFile;
        }
    }
    _render() {
        const iconColor = this._settings.iconColor ?? "#f2b544";
        const iconSize = this._settings.iconSize ?? 72;
        const conditionColor = this._settings.conditionColor ?? "#e6e6e6";
        const tempColor = this._settings.tempColor ?? "#ffffff";
        const tempUnit = this._settings.tempUnit ?? "celsius";
        const {family: conditionFontFamily, size: conditionFontSize} = _parseFontDescription(this._settings.conditionFont ?? "Sans 18", "Sans", 18);
        const {family: tempFontFamily, size: tempFontSize} = _parseFontDescription(this._settings.tempFont ?? "Sans Bold 40", "Sans Bold", 40);
        _deferUntilMapped(this._actor, () => {
            applyLayeredCardStyle(this._layers, this._settings, {
                backgroundColorKey: "cardColor",
                cornerRadiusFallback: 18
            }, false);
            this._content.set_style("padding: 20px 26px; spacing: 20px;");
        });
        const iconKey = this._weather?.icon ?? "weather-cloud";
        const iconFile = this._getColoredIconFile(iconKey, iconColor);
        if (iconFile) {
            const gicon = new Gio.FileIcon({
                file: iconFile
            });
            this._iconBin.set_child(new St.Icon({
                gicon: gicon,
                icon_size: iconSize
            }));
        } else {
            this._iconBin.set_child(null);
        }
        let tempText = "--";
        if (this._weather) {
            const value = tempUnit === "fahrenheit" ? this._weather.tempF : this._weather.tempC;
            if (typeof value === "number") tempText = `${Math.round(value)}°`;
        }
        this._tempLabel.set_text(tempText);
        this._tempLabel.set_style(`color: ${tempColor}; font-family: ${tempFontFamily}; ` + `font-size: ${tempFontSize}px; font-weight: bold;`);
        this._conditionLabel.set_text(this._weather ? this._trCondition(this._weather.condition) : "--");
        this._conditionLabel.set_style(`color: ${conditionColor}; font-family: ${conditionFontFamily}; ` + `font-size: ${conditionFontSize}px;`);
    }
}