#!/usr/bin/env bash

fuzzySelect(){
	cd "$dataDir" || return
	local id
	local query
	local operation
	local output
	local header="$(echo -e "Type to filter

${YELLOW}ctrl+n $WHITE create new      ${YELLOW}ctrl+v $WHITE view selected
${YELLOW}ctrl+e $WHITE edit selected   ${YELLOW}ctrl+d $WHITE delete selected
")"
	export -f fzfPreview
	export dataDir
	output="$(listEntries |
		fzf --header="$header" --header-lines=2 --print-query \
		--delimiter="  +" --with-nth=3,5 --height=100% \
		--expect="ctrl-n,ctrl-v,ctrl-e,ctrl-d"  \
		--preview='bash -c "fzfPreview {}"')" || true

	query="$(echo "$output" | sed -n '1p')"
	operation="$(echo "$output" | sed -n '2p')"
	id="$(echo "$output" | sed -n '3p' | cut -d' ' -f1)"

	case "$operation" in
		'ctrl-n') newFile "$query" ;;
		'ctrl-v') viewFile "$id" ;;
		'ctrl-e') editFile "$id" ;;
		'ctrl-d') deleteFile "$id" ;;
		'')
			case "$1" in
				edit) editFile "$id" ;;
				view) viewFile "$id" ;;
				*) viewFile "$id" ;;
			esac
			;;
		*) die "unknown operation '$operation'" ;;
	esac

}

fzfPreview(){
	cd "$dataDir" || return

	local id
	local filename
	local title
	local type
	local tags

	id="$(echo "$1" | awk -F '  +' '{print $1}')"
	filename="$(echo "$1" | awk -F '  +' '{print $2}')"
	title="$(echo "$1" | awk -F '  +' '{print $3}')"
	type="$(echo "$1" | awk -F '  +' '{print $4}')"
	tags="$(echo "$1" | awk -F '  +' '{print $5}')"

	if [ "$type" = "normal" ]; then
		bat --color=always --style=full "$filename"
	fi
}

doDeepSearch(){
	cd "$dataDir" || return
	local query="$1"
	echo "$query"
	rg --column --line-number --no-heading --color=always --smart-case "$query"
}

doDeepPreview(){
	cd "$dataDir" || return
	local file
	local line
	file="$(echo "$1" | cut -d ':' -f 1)"
	line="$(echo "$1" | cut -d ':' -f 2)"
	bat --color=always --style=full -H "$line" "$file"
}

deepSearch(){
	type -p rg > /dev/null || die "You need rg installed for deep search"
	export -f doDeepSearch
	export -f doDeepPreview
	export dataDir
	echo "" | fzf --ansi \
		--bind 'change:reload:bash -c "doDeepSearch {q} || true"' \
		--preview 'bash -c "doDeepPreview {} || true"'
}