#!/bin/bash

set -Eeu -o pipefail

VALUE_COLOR=${color:-$(xrescat i3xrocks.value.color "#D8DEE9")}
VALUE_FONT=${font:-$(xrescat i3xrocks.value.font "Source Code Pro Medium 13")}
BUTTON="${button:-}"

# Information on the various formats: https://github.com/chubin/wttr.in
VALUE_WEATHER_FORMAT=${weather_format:-$(xrescat i3xrocks.weather.format "1")}
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
ACTION_WEATHER_UNIT=""
WEATHER_UNIT=${weather_unit:-$(xrescat i3xrocks.weather.units "")}
if [ -n "${WEATHER_UNIT}" ]; then
    ACTION_WEATHER_UNIT="?${WEATHER_UNIT}"
    WEATHER_UNIT="&${WEATHER_UNIT}"
fi

# Defaults to IP address location
VALUE_WEATHER_LOCATION=${weather_location:-$(xrescat i3xrocks.weather.location "")}
VALUE_WEATHER_ERROR_MESSAGE=${error_message:-$(xrescat i3xrocks.weather.error_message $'\u26D4')}
WEATHER=$(curl -sS "https://wttr.in/${VALUE_WEATHER_LOCATION}${VALUE_WEATHER_FORMAT}${WEATHER_UNIT}" || echo "${VALUE_WEATHER_ERROR_MESSAGE}")

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

echo "<span font_desc=\"${VALUE_FONT}\" color=\"${VALUE_COLOR}\">${WEATHER}</span>"

if [ ! "x${BUTTON}" == "x" ]; then
    ACTION=$(xrescat i3xrocks.action.weather "xdg-open https://wttr.in/${VALUE_WEATHER_LOCATION}${ACTION_WEATHER_UNIT}")
    /usr/bin/i3-msg -q exec "$ACTION"
fi
