#!/bin/sh

template="{{.Key}} {{.Created.AsTime.Year}}-{{.Created.AsTime.Month}}-{{.Created.AsTime.Day}} {{.Taglist}} {{.Preview}}"
header="TITLE DATE TAGS PREVIEW"

# its possible to use another version of anydb for testing purposes
anydb="${ANYDB:-anydb}"

# list command
command="( echo '$header'; $anydb ls -m template --template '$template' ) | column -t -l4"

for binary in fzf $anydb column diff awk less; do
    if ! type $binary > /dev/null 2>&1; then
        echo "$binary is not installed!"
        exit 1
    fi
done

if type gum > /dev/null 2>&1; then
    GUM=1
fi

_rand() {
    awk 'BEGIN {srand(); printf( "%d\n", 1024 * rand() )}'
}

_list() {
    (
        echo "$header"
        $anydb ls -m template --template "$template"
    ) | column -t -l4
}

_updater() {
    _port="$1"
    _cache="/tmp/anydbcache.$port"
    _current="/tmp/anydbcache.$port.current"

    touch $_current $_cache

    while :; do
        sleep 10

        _list > $_current

        if ! diff -q $_current $_cache > /dev/null 2>&1; then
            curl -d "reload($command)+clear-screen" "http://127.0.0.1:$_port"
        fi
        cp $_current $_cache
    done
}

_cleanup() {
     # get rid of the update child
    kill $pid

    # clean up reloader cache
    rm -f /tmp/anydbcache.${port}*
}



# fork background updater
port=$((8000 + $(_rand) % 1000))
_updater $port &
pid=$!

db=$($anydb info | grep Database | cut -d: -f2)
shorthelp="$db - [enter]read  [c-e]edit  [c-k]kill  [c-c]exit  [c-k]delete"

if test -n "$GUM"; then
    color="Color \"#ff\" \"#0000ff\"" # white on blue
    db="{{ $color \"Database:\"}}$db"
    enter="{{ $color \"[Enter]\"}} Read"
    edit="{{ $color \"[ctrl-c]\"}} Edit"
    delete="{{ $color \"[ctrl-k]\"}} Delete"
    template="$db $enter $edit $delete"
    shorthelp=$(echo "$template" | gum format -t template)
fi

trap '_cleanup; (exit $?); exit' INT TERM EXIT

: | command="$command" fzf \
           --bind "start:reload:$command" \
            --header-lines 1 --layout=reverse --info=inline \
            --height 100% --pointer="→" --separator="─" \
            --scrollbar="│" --preview-window "right:50%" \
            --border-label="$shorthelp" \
            --border=bottom --layout=reverse --info=inline \
            --height 100% --header-first --cycle --header-lines=1 --listen=$port \
            --bind "enter:execute: clear; $anydb get {1} | less" \
            --bind "ctrl-e:execute: $anydb edit {1}" \
            --bind "ctrl-k:execute:$anydb del {1}"
            

