#!/usr/bin/env bash

SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT")
cd "$SCRIPTPATH" || exit

for c in sk bat yq; do
	if ! command -v ${c} &>/dev/null; then
		echo "$command ${c} could not be found"
		exit 1
	fi
done

SWITCH_MENU=$(mktemp)

function update() {
	touch commands.state
	if [[ "$(stat -c%Y commands.yaml)" != "$(cat commands.state)" ]] || [[ $1 == "force" ]]; then
		cat /dev/null >commands.raw
		i=1
		#set -eux
		while read -r line; do
			cmd=$(echo "${line}" | yq -r .cmd)
			lang=$(echo "${line}" | yq -r .lang)
			tags=$(echo "${line}" | yq -r .tags)
			desc=$(echo "${line}" | yq -r .desc)
			if [[ $cmd == "null" ]] || [[ $lang == "null" ]] || [[ $tags == "null" ]] || [[ $desc == "null" ]]; then
				echo "Error on line: ${line}"
				exit
			fi
			echo "${cmd} # [${tags} ${lang} ${i}] ${desc}" | tee -a commands.tmp.${lang} >/dev/null
			i=$(($i + 1))
		done < <(cat commands.yaml | yq e -o=j -I=0 .commands[])
		for filename in $(ls -t commands.tmp.*); do
			lang=$(echo ${filename} | rev | cut -d'.' -f1 | rev)
			cat ${filename} | bat --color=always -l ${lang} -pp >>commands.raw
			rm -f ${filename}
		done
		stat -c%Y commands.yaml >commands.state
	fi
}

function notes() {
	update
	echo -n 0 >${SWITCH_MENU}
	unset RES
	RES=$(cat commands.raw | sk --reverse --ansi --inline-info \
		--bind "shift-left:execute-silent(echo -n 1 > ${SWITCH_MENU})+abort" \
		--bind "shift-right:execute-silent(echo -n 1 > ${SWITCH_MENU})+abort")
	SWITCH=$(cat ${SWITCH_MENU})
	if [[ ${SWITCH} -eq 1 ]]; then
		manuals
	fi
	if [[ ! -z "${RES}" ]]; then
		echo -n ${RES} | grep -o ".*#" | sed 's/ #$//g'
	fi
	rm -f ${SWITCH_MENU}
	exit
}

function manuals() {
	echo -n 0 >${SWITCH_MENU}
	unset RES
	RES=$(man -k . | bat --color=always -pp - | sk --reverse --ansi --inline-info --keep-right \
		--bind "shift-left:execute-silent(echo -n 1 > ${SWITCH_MENU})+abort" \
		--bind "shift-right:execute-silent(echo -n 1 > ${SWITCH_MENU})+abort")
	SWITCH=$(cat ${SWITCH_MENU})
	if [[ ${SWITCH} -eq 1 ]]; then
		notes
	fi
	if [[ ! -z "${RES}" ]]; then
		echo -n man $(echo ${RES} | cut -d' ' -f1)
	fi
	rm -f ${SWITCH_MENU}
	exit
}

function copy() {
	cat "${COPY_SRC}" >"${1}"
}

function _usage() {
	echo "Invalid command. Usage: ${0} <${actions[@]}> <context>"
	exit 1
}

actions=$(declare -F | grep -v _ | cut -d' ' -f3 | xargs)
if [[ ! " ${actions[*]} " =~ [[:space:]]${1}[[:space:]] ]]; then
	_usage
else
	${1} ${2} ${3}
fi
