#!/bin/bash

set -e

subcommand=""
filepath=""
searchquery=""
uuid=""

show_help() {
cat <<EOF
Usage: foo <<options>> <bar>

Blubber blah blah ...
EOF
}

while [[ "$#" -gt 0 ]]; do
	case "$1" in
		--file) filepath="$2"; shift 2;;
		--uuid) uuid="$2"; shift 2;;
		
		--help) show_help; exit 0;;
		view) subcommand="$1"; shift 1;;
		search) subcommand=search; searchquery="$2"; shift 2;;
		notify|add|fzf|fzf-konsole) subcommand="$1"; shift 1;;
		open)
			if [ "$#" -gt 1 ] ; then
				subcommand=view
				filepath="$1"
				shift 2
			else
				subcommand=fzf-konsole
				shift
			fi
			;;
		*) printf "Unknown option: %s\n" "$1"; exit 1;;
	esac
done

function notification() {
	n="$(reminderfile query --before "$(date --date "1 day" +@%s)" --json | jq '.|length')"
	answer="$(notify-send "Sie haben $n Erinnerungen" -A "Ansehen")"

	case "$answer" in
		0)
			notify-send "Geht noch net …"
			;;
	esac
}

function d() {
	date --date "$1"
}

function human_date_to_unix() {
	[ -n "$1" ] || return
	date --date \
	"$(
		tr 'A-Z' 'a-z' <<< "$1" |
		tr '_+' '  ' |
		sed \
		-e "s/heute/today/" \
		-e "s/in//" \
		-e "s/morgen/tomorrow/" \
		-e "s/montag/mon/" \
		-e "s/dienstag/tue/" \
		-e "s/mittwoch/wed/" \
		-e "s/tage?/days/" \
		-e "s/wochen?/weeks/" \
		-e "s/monate?n?/months/" \
		-e "s/jahre?n?/years/" \
		-e "s/um//" \
		-e "s/uhr//"
	)" +@%s
}

function choose_attachment() {
	file_or_directory="$(
		kdialog --title "$title" \
			--radiolist "Soll eine Datei oder ein Ordner angehängt werden?" \
			file "📎 Eine Datei anhängen" off \
			folder "📁 Einen Ordner anhängen" on \
			nothing "Kein Anhang" off
	)"
	subject=""
	filepath=""
	case "$file_or_directory" in
		file)
			filepath="$(kdialog --getopenfilename --title "Datei zur Wiedervorlage am $(d "$date") auswählen.")"
			;;
		folder)
			filepath="$(kdialog --getexistingdirectory --title "Ordner zur Wiedervorlage am $(d "$date") auswählen.")"
			subject=" von $(basename -- "$filepath")"
			;;
		"")
			return 1
			;;
	esac
	printf "%s\n" "$filepath"
}

function show_reminder_file() {
		date="@$(jq -r .unixtime < "$FILE")"
		attachment="$(jq -r .file < "$FILE")"
		description="$(jq -r .description < "$FILE")"

		attachment_name="Kein Anhang"
		if [ -n "$attachment" ] ; then
			attachment_name="$(basename "$attachment")"
		fi

		res="$(kdialog \
			--radiolist "Wiedervorlage am $(d "$date")." \
			--title "Erinnerung bearbeiten" \
			"desc"       "✏ Beschreibung: $description" ""\
			"date"       "🗓 Am: $(d "$date")" ""\
			"attachment" "📎 Anhang: $attachment_name" ""\
			"open-attachment" "Anhang öffnen" ""\
			"delete"     "🗑️ Erinnerung Löschen" ""
		)"

		if [ "$?" != "0" ] ; then
			exit
		fi

		case "$res" in
			desc)
				new_desc="$(kdialog --textinputbox "" \
					"$description" \
					--title "Wiedervorlage am $(d "$date") - Beschreibung" \
					--ok-label "Speichern"
					)"
					
				if [ -n "$new_desc" ] ; then
					json="$(cat "$FILE")"
					printf "%s" "$json" |
					jq --arg "desc" "$new_desc" '.description=$desc' > "$FILE"
				fi
				;;
			date)
				new_date="$(
					kdialog --title "$title" \
						--ok-label "Speichern"
						--calendar "Wann soll die Wiedervorlage stattfinden?" \
						--dateformat "yyyy-MM-dd" || true
				)"
				if [ -n "$new_date" ] ; then
					json="$(cat "$FILE")"
					printf "%s" "$json" |
					jq --argjson "date" "$( date --date "$new_date" +%s )" '.unixtime=$date' > "$FILE"
				fi
				
				;;
			attachment)
				cd "$(basedir "$attachment" || true )" || true
				new_attachment="$(choose_attachment)"
				if [ $? = 0 ] ; then
					json="$(cat "$FILE")"
					printf "%s" "$json" |
					jq --arg "file" "$new_attachment" '.file=$file' > "$FILE"
				fi
				;;
			open-attachment)
				if "$attachment" ; then
					xdg-open "$attachment"
				else
					notify-send "Kann nicht vorhandenen Anhang nicht öffnen."
				fi
			;;
			delete)
				kdialog --warningyesno "Die Erinnerung am $(d "$date") wurde gelöscht" \
				--yes-label "Ist okay" --no-label "Rückgängig machen" || return
				trash-put "$FILE"
				exit
			;;
		esac

}

fzf_gui() {
	while true ; do
		result="$(
			reminderfile query \
			| fzf --disabled \
				--bind "change:reload:$0 search {q}"
		)"
		if [ $? != 0 ] ; then
			break
		fi
		if [ -n "$result" ] ; then
			"$0" view --uuid "$( printf "%s\n" "$result" | awk '{ print $1 }' )" &
		fi
	done
}

if [ "$subcommand" = open ] ; then
	if [ -n "$filepath" ] ; then
		subcommand="view"
	else
		subcommand="fzf-konsole"
	fi
fi

case "$subcommand" in
	notify)
		notification &
		;;
	add)
		title="Wiedervorlage"
		if [ -z "$date" ] ; then
			date="$(
				kdialog --title "$title" \
					--calendar "Wann soll die Wiedervorlage stattfinden?" \
					--dateformat "yyyy-MM-dd" || true
			)"
			if [ -z "$date" ] ; then
				notify-send "Abgebrochen"
				exit 0
			fi
		fi
		title="$title $(d "$date")"
		if [ -z "$filepath" ] ; then
			filepath="$(choose_attachment)"
		fi
		[ -z "$filepath" ] || filepath="$(realpath "$filepath")"
		subject=""
		[ -z "$filepath" ] || subject=" von $(basename -- "$filepath")"
		title="$title$subject"
		set +e
		description="$(
			kdialog --title "$title" \
				--textinputbox "Information zur $title" "Wiedervorlage$subject:\n"
		)"
		if [ $? != 0 ] ; then
			notify-send "Abgebrochen"
			exit 0
		fi
		set -e
		uuid="$(reminderfile add --file "$filepath" --description "$description" --date "$date")"
		FILE="$(reminderfile get-file --uuid "$uuid")"
		notify-send "Wiedervorlage hinzugefügt" "am $(d "$date")$subject"
		while true ; do
			show_reminder_file "$FILE"
		done
		;;
	view)
		file="$filepath"
		[ -z "$uuid" ] || FILE="$(reminderfile get-file --uuid "$uuid")"
		if ! [ -f "$FILE" ] ; then
			kdialog --title "Kann die Erinnerung nicht finden." \
				--error "Kann die Erinnerung mit der id '${uuid:-$filepath}' nicht finden."
		fi
		while true; do
			show_reminder_file "$FILE"
		done
		
		;;
	search)
		date="$(grep -o "am:[^ ]*" <<< "$searchquery" | sed 's/^am://')"
		date_before="$(grep -o "vor:[^ ]*" <<< "$searchquery" | sed 's/^vor://')"
		date_after="$(grep -o "nach:[^ ]*" <<< "$searchquery" | sed 's/^nach://')"
		file="$(grep -o "datei:[^ ]*" <<< "$searchquery" | sed 's/datei://')"

		searchquery="$(
			sed \
				-e "s/am:[^ ]*//" \
				-e "s/vor:[^ ]*//" \
				-e "s/nach:[^ ]*//" \
				-e "s/datei:[^ ]*//" \
				<<< "$searchquery"
		)"

		reminderfile query \
			--date "$(human_date_to_unix "$date")" \
			--before "$(human_date_to_unix "$date_before")" \
			--after "$(human_date_to_unix "$date_after")" \
			--file "$file" \
			| fzf --filter="$searchquery"
		;;
	fzf-konsole)
		exec konsole -e "$0" fzf
		;;
	fzf)
		fzf_gui
		;;
esac
