#!/bin/bash

RESULT_FILE="${XDG_CONFIG_HOME:-$HOME/.config}/qalculate/qalc.result.history"
if [ ! -f "$RESULT_FILE" ]; then
	touch "$RESULT_FILE"
fi

handleResult() {
	PASTE_TIMEOUT="45s"
	wl-copy "$1"
	notify-send "Copied result in clipboard for $PASTE_TIMEOUT" "$2"
	sleep "$PASTE_TIMEOUT"
	wl-copy "$3"
}

LAST_LAUNCHER=""
QALC_RET=""
while :
do
	qalc_hist=$(tac "$RESULT_FILE" | head -1000)
	LAUNCHER_RET=$({{ launcher }} {{ dmenu_flag }} -p 'Calculate{{ (launcher == 'fuzzel') | ternary(': ', '') }}' <<< "$qalc_hist")
	rtrn=$?

	if [ "$LAUNCHER_RET" = "clean" ]; then
		rm -f "$RESULT_FILE"
		touch "$RESULT_FILE"
		continue
	fi

	if [ ! "$rtrn" = "0" ]; then
		if [ -n "$LAST_LAUNCHER" ]; then
			RESULT=$(qalc -t "$LAST_LAUNCHER")
			handleResult "$RESULT" "$LAST_LAUNCHER" "$PREVIOUS_PASTE"
		fi
		exit 0
	fi

	if [[ "$LAUNCHER_RET" =~ .*=.* ]]; then
		RESULT=$(echo "$LAUNCHER_RET" | awk '{print $NF}')
		PREVIOUS_PASTE=$(wl-paste)
		handleResult "$RESULT" "$LAUNCHER_RET" "$PREVIOUS_PASTE"
		exit 0
	else
		QALC_RET=$(qalc "$LAUNCHER_RET")
		LAST_LAUNCHER=$LAUNCHER_RET
		echo "$QALC_RET" >> "$RESULT_FILE"
	fi
done
