#!/bin/bash

set -Eeu -o pipefail

# Simplified weather script for i3status-rust
# Based on the original weather script but adapted for Sway/i3status-rust

# Information on the various formats: https://github.com/chubin/wttr.in
VALUE_WEATHER_FORMAT=${weather_format:-"%c%f"}
VALUE_WEATHER_FORMAT="?format=${VALUE_WEATHER_FORMAT}"

# Determine units to use for temperature
# We don't supply a default here because wttr.in is "smart" enough to choose for us
WEATHER_UNIT=${weather_unit:-""}
if [ -n "${WEATHER_UNIT}" ]; then
    WEATHER_UNIT="&${WEATHER_UNIT}"
fi

# Location (defaults to Pärnu as in your original script)
VALUE_WEATHER_LOCATION=${weather_location:-"Pärnu"}
VALUE_WEATHER_ERROR_MESSAGE=${error_message:-"⛔"}
VALUE_FETCH_WEATHER_URL="https://wttr.in/${VALUE_WEATHER_LOCATION}${VALUE_WEATHER_FORMAT}${WEATHER_UNIT}"

# Get weather data
WEATHER=$(curl -sS "$VALUE_FETCH_WEATHER_URL" 2>/dev/null || echo "${VALUE_WEATHER_ERROR_MESSAGE}")

# Get sunrise/sunset data
VALUE_SUNSET_SUNRISE_FORMAT="?format=%S-%s%20%m+"
SUNRISE_SUNSET=$(curl -sS "https://wttr.in/${VALUE_WEATHER_LOCATION}${VALUE_SUNSET_SUNRISE_FORMAT}${WEATHER_UNIT}" 2>/dev/null || echo "")

if [ -n "$SUNRISE_SUNSET" ]; then
    SUNRISE_VALUE=$(echo ${SUNRISE_SUNSET} | cut -c 1-5)
    SUNSET_VALUE=$(echo ${SUNRISE_SUNSET} | cut -c 10-14)
    SUNRISE_SUNSET_TEXT=" (${SUNRISE_VALUE}-${SUNSET_VALUE})"
else
    SUNRISE_SUNSET_TEXT=""
fi

# Check for errors
if echo "${WEATHER}" | grep -q -P "Unknown\slocation"; then
    WEATHER=${VALUE_WEATHER_ERROR_MESSAGE}
fi

# Output for i3status-rust (plain text)
echo "${WEATHER}${SUNRISE_SUNSET_TEXT}"

# Handle click events (for i3status-rust custom block)
if [ "${BLOCK_BUTTON:-}" = "1" ]; then
    # Left click - show detailed weather
    FULL_WEATHER=$(curl -sS "https://wttr.in/${VALUE_WEATHER_LOCATION}?format=%l:+%c+%f+%h+%p+%P+%m+%w+%S+%s" 2>/dev/null || echo "${VALUE_WEATHER_ERROR_MESSAGE}")
    notify-send "Weather Details" "$FULL_WEATHER" -t 10000
elif [ "${BLOCK_BUTTON:-}" = "3" ]; then
    # Right click - open weather website
    xdg-open "https://wttr.in/${VALUE_WEATHER_LOCATION}" >/dev/null 2>&1 &
fi 