#!/usr/bin/env bash

RESULT_FILE="$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_WOFI=""
QALC_RET=""
while :
do
    qalc_hist=$(tac "$RESULT_FILE" | head -1000)
    WOFI_RET=$(wofi --sort-order=default --cache-file=/dev/null -W "40%" -d -p calc <<< "$qalc_hist")
    rtrn=$?

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

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

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