#!/usr/bin/env zsh
# edit all source files of type under a directory

local search_map
typeset -A search_map
local keys
typeset -a keys
local k
local koff
local i
typeset -i i
local char
local input
local file_list
typeset -a file_list

search_map=(
	"c"        "\.(c|h)"
	"crystal"  "\.cr"
	"css"      "\.(css|scss)"
	"elixir"   "\.(ex|exs)"
	"go"       "\.go"
	"html"     "\.(html|xhtml)"
	"markdown" "\.md"
	"ocaml"    "\.(ml|mli)"
	"js"       "\.js"
	"tex"      "\.tex"
	"vim"      "\.vim"
)

{
	printf "%s\0" ${(k)search_map} | sort -z | head -c -1
	printf "\n"
} | IFS=$'\0' read -r -A keys

[[ $#@ -eq 0 ]] && return
[[ $EDITOR == "" ]] && return

zmodload zsh/curses || return

zcurses init

function draw_main() {
	zcurses clear stdscr

	width=$COLUMNS

	zcurses attr stdscr +bold

	if [[ $width -ge 16 ]]; then
		zcurses move stdscr 0 $(($width / 2 - 8))
		zcurses string stdscr "select a filetype"
	else
		zcurses move stdscr 0 0
		zcurses string stdscr "sel"
	fi

	zcurses attr stdscr -bold

	for i in {1..$#keys}; do
		zcurses move stdscr $((1 + i)) 0
		zcurses string stdscr $keys[$i]
	done
}

trap 'draw_main' WINCH

draw_main

input=""

while true; do
	zcurses move stdscr $(($#search_map + 3)) 0
	zcurses clear stdscr bot
	zcurses string stdscr "-: $input"
	zcurses refresh stdscr

	char=""
	sleep 0
	zcurses timeout stdscr 100
	zcurses input stdscr char
	
	# clear
	[[ $char == "" || $char == "" ]] && input="" && continue

	# backspace
	[[ $char == "" && $input != "" ]] && input=${input:0:-1} && continue

	# tab complete
	if [[ $char == $'\t' ]]; then
		seen="false"

		for k in ${(@k)search_map}; do
			[[ $k =~ "^${input}.*$" ]] || continue
			[[ $seen == "true" ]] && seen="false" && break
			seen="true"
			koff=$k
		done

		[[ $seen == "true" ]] && input=$koff

		continue
	fi

	# select
	[[ $char == $'\n' || $char == "" ]] && break

	# add single alphanum
	[[ $char =~ "^[a-zA-Z0-9]$" ]] || continue

	input="$input$char"
done

zcurses end

[[ $input == "" || $search_map[$input] == "" ]] && return

{
	find $@ \
		-regextype posix-extended \
		-regex "^(/[^.]|[^/])*$search_map[$input]\$" \
		-print0 \
	| head -c -1
	printf "\n"
}| IFS=$'\0' read -r -A file_list

[[ $#file_list -ne 0 ]] && $EDITOR -- $file_list