#!/bin/sh

# Displays todays precipication chance () and daily low () and high ().
# Usually intended for the statusbar.

# If we have internet, get a weather report from wttr.in and store it locally.
# You could set up a shell alias to view the full file in a pager in the
# terminal if desired. This function will only be run once a day when needed.
weather_report="${XDG_DATA_HOME:-$HOME/.local/share}/weather_report"

get_forecast() {
    curl -sf "wttr.in/$LOCATION?format=j1" > "$weather_report" || exit 1
}

codes="113=
116=
119=
122=
143=
176=
179=
182=
185=
200=
227=
230=
248=
260=
263=
266=
281=
284=
293=
296=
299=
302=
305=
308=
311=
314=
317=
320=
323=
326=
329=
332=
335=
338=
350=
353=
356=
359=
362=
365=
368=
371=
374=
377=
386=
389=
392=
395="

show_weather() {
    weather_code="$(cat "$weather_report" | jq -r '.current_condition[0].weatherCode')"
    temperature="$(cat "$weather_report" | jq -r '.current_condition[0].FeelsLikeC')"

    echo "$codes" | sed -n "/$weather_code/{s/[0-9]*=//;p;q}" | tr -d '\n'

    symbol="$([[ $temperature -lt 15 ]] && echo  || echo )"

    echo " $temperature $symbol"
}

case $BLOCK_BUTTON in
	1) setsid -f "$TERMINAL" -e curl "wttr.in/$LOCATION";;
	2) get_forecast && show_weather ;;
	3) notify-send "🌈 Weather module" "\- Left click for full forecast.
- Middle click to update forecast." ;;
	6) "$TERMINAL" -e "$EDITOR" "$0" ;;
esac

# The test if our forcecast is updated to the day. If it isn't download a new
# weather report from wttr.in with the above function.
[ "$(stat -c %y "$weather_report" 2>/dev/null | cut -d' ' -f1)" = "$(date '+%Y-%m-%d')" ] ||
	get_forecast

show_weather
