#!/bin/sh

source ~/.config.env

weatherreport="${XDG_DATA_HOME:-$HOME/.local/share}/weatherreport"
weatherreportjson="${XDG_DATA_HOME:-$HOME/.local/share}/weatherreportjson"

WCODES=(
    ["113"]="^c#ebcb8b^"
    ["116"]="^c#ebcb8b^杖"
    ["119"]="摒"
    ["122"]=""
    ["143"]=""
    ["176"]="^c#81a1c1^"
    ["179"]="^c#81a1c1^"
    ["182"]="^c#81a1c1^"
    ["185"]="^c#81a1c1^"
    ["200"]=""
    ["227"]=""
    ["230"]=""
    ["248"]=""
    ["260"]=""
    ["263"]="^c#81a1c1^"
    ["266"]="^c#81a1c1^"
    ["281"]="^c#81a1c1^"
    ["284"]="^c#81a1c1^"
    ["293"]="^c#81a1c1^"
    ["296"]="^c#81a1c1^"
    ["299"]="^c#81a1c1^"
    ["302"]="^c#81a1c1^"
    ["305"]="^c#81a1c1^"
    ["308"]="^c#81a1c1^"
    ["311"]="^c#81a1c1^"
    ["314"]="^c#81a1c1^"
    ["317"]="^c#81a1c1^"
    ["320"]=""
    ["323"]="^c#81a1c1^"
    ["326"]="^c#81a1c1^"
    ["329"]=""
    ["332"]=""
    ["335"]="^c#81a1c1^"
    ["338"]=""
    ["350"]="^c#81a1c1^"
    ["353"]="^c#81a1c1^"
    ["356"]="^c#81a1c1^"
    ["359"]="^c#81a1c1^"
    ["362"]="^c#81a1c1^"
    ["365"]="^c#81a1c1^"
    ["368"]="^c#81a1c1^"
    ["371"]="^c#81a1c1^"
    ["374"]="^c#81a1c1^"
    ["377"]="^c#81a1c1^"
    ["386"]="^c#81a1c1^"
    ["389"]="^c#81a1c1^"
    ["392"]="^c#81a1c1^"
    ["395"]="^c#81a1c1^"
)

getforecast() { curl -sf "wttr.in/$LOCATION" > "$weatherreport" || exit 1 ;}
getforecastjson() { curl -sf "wttr.in/$LOCATION?format=j1" > "$weatherreportjson" || exit 1 ;}

# Some very particular and terse stream manipulation. We get the maximum
# precipitation chance and the daily high and low from the downloaded file and
# display them with coresponding emojis.
showweather() {
    data=$(jq -r ".weather|.[0]|.hourly|.[$(expr $(date '+%H') / 4)]|.FeelsLikeC,.chanceofrain,.chanceofsnow,.WindGustKmph,.weatherCode" "$weatherreportjson")
    data=$(echo -ne $(echo $data | cut -d' ' -f 1-4)" ${WCODES[$(echo $data | cut -d' ' -f 5)]}")
    echo $data | awk -F' ' '{
		if ($4 > 30)
			print "^c#ffffff^  ^d^" $4 "kh "$5 " ^d^ " $1 "°"
		else if ($2 < $3)
			print "^c#ffffff^ ^d^" $3 "% "$5 " ^d^ " $1 "°"
		else
			print "^c#81a1c1^ ^d^" $2 "% " $5 " ^d^ " $1 "°"}'
}

case $BLOCK_BUTTON in
	1) setsid -f st -c weather -n weather -e less -Srf "$weatherreport" ;;
	2) getforecast && showweather && kill -50 $(pidof dwmblocks) ;;
	3) notify-send " Weather module" "\- Left click for full forecast.
- Middle click to update forecast.
: Chance of rain/snow
ﰕ: Daily low
滛: Daily high" ;;
	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.
[ "$(date -r "/home/yigit/.local/share/weatherreport" "+%d-%m-%Y")" = "$(date '+%d-%m-%Y')" ] ||
	getforecast

[ "$(date -r "/home/yigit/.local/share/weatherreportjson" "+%d-%m-%Y %H")" = "$(date '+%d-%m-%Y %H')" ] ||
	getforecastjson

showweather
