const { Widget } = ags;
const { execAsync } = ags.Utils;
import barConfig from '../barConfig.js';
import { getWeatherSymbol, getTemp, getWeatherDesc } from '../lib.js';

export const Weather = () => Widget.Box({
    halign: 'end',
    tooltipText: 'Weather',
    valign: 'center',
    style: 'margin-right: 2.5rem;',
    children: [
        Widget.Label({
            halign: 'end',
            valign: 'center',
            className: 'txt-larger txt icon-material',
            style: 'margin-right: 0.5rem; margin-top: 1px;',
            label: 'rainy',
        }),
        Widget.Label({
            halign: 'end',
            valign: 'center',
            className: 'txt-norm txt',
        }),
    ],
    connections: [[barConfig?.weatherUpdateInterval * 1000, async box => {
        setTimeout(() => getWeather(box), 10000);
    }]],
});

async function getWeather(box) {
    let latLng = [0, 0];
    execAsync(`curl https://geocoding-api.open-meteo.com/v1/search?name=${barConfig?.city}&count=1&language=en&format=json`)
        .then(output => {
            const geocoding = JSON.parse(output);
            if (geocoding.results.length === 0) {
                return;
            }
            latLng = [geocoding.results[0].latitude, geocoding.results[0].longitude];
            execAsync(`curl https://api.open-meteo.com/v1/forecast?latitude=${latLng[0]}&longitude=${latLng[1]}&current=temperature_2m,is_day,weather_code`)
                .then(output => {
                    const weather = JSON.parse(output);
                    const weatherCode = weather.current.weather_code;
                    box.tooltipText = getWeatherDesc(weatherCode);
                    box.children[0].label = getWeatherSymbol(weatherCode);
                    box.children[1].label = getTemp(Math.round(weather.current.temperature_2m) + "");
                }).catch(console.error)
        }).catch(console.error)
}