# Basic vars
set ratios 1:2:5
set shellopts '-eu'
set ifs "\n"
set findlen 1
set scrolloff 10
set icons
set wrapscroll
set period 1
set cursorpreviewfmt "\033[7;90m"
set promptfmt # this is set in a function later

# HACK: This is needed to trigger the opening function of the taolf nvim plugin
cmd open ${{
    set +u
    files=${@:-$fx}
    [ "$lf_user_multiedit" = "true" ] && {
        if [ -z "$TAOLF" ]; then
            $EDITOR $fx
            return
        fi
    }
    $OPENER "$f"
}}

cmd pushedit %{{
    set +u
    files=$1
    [ -z $files ] && {
        echo "Open: " && read -r files
        echo
    }
    echo $files | xargs -r touch
    if [ -n "$TAOLF" ]; then
        set -- $files
        lf -remote "send $id unselect
        send $id toggle $files
        send $id select $1
        send $id open"
    else
        lf -remote "send $id \$$OPENER $files"
    fi
}}

cmd open-with ${{
    method=$(rifle -c $XDG_CONFIG_HOME/lf/rifle.conf -l $fx | fzf --header="Choose an application:" | cut -d':' -f1)
    rifle -c $XDG_CONFIG_HOME/lf/rifle.conf -p $method $fx
}}

cmd trash &{{
    for f in $fx; do
        trash-put $f &
    done
    lf -remote "send load"
}}

cmd lazygit %{{
    dir=$(dirname "$(realpath "${f:-_}")"})
    if ! git --noglob-pathspecs -C $dir status >/dev/null 2>&1; then
        echo "Initialize git repo in '${dir}' [Y/n]:" && read yn &&
        case $yn in
            "" | [Yy]*) git -C ${dir} init >/dev/null 2>&1; break ;;
            [Nn]*) ;;
        esac
    fi
    lf -remote "send $id \$cd '$dir' && lazygit"
}}

# y (select for copy) and P to paste soft-link
# d (select for cut) and P to paste hard-link
cmd link &{{
    set -- $(cat ~/.local/share/lf/files)
    mode="$1"
    shift
    if [ "$#" -lt 1 ]; then
        lf -remote "send $id echo no files to link"
        exit 0
    fi
    case "$mode" in
        # symbolically copy mode is indicating a soft link
        copy) ln -sr -t . -- "$@";;
        # while a move mode is indicating a hard link
        move) ln -t . -- "$@";;
    esac
    rm ~/.local/share/lf/files
    lf -remote "send clear"
}}

cmd bulkrename $vidir

cmd on-cd &{{
    lf -remote "send $id set promptfmt \"$(zsh -c 'source $ZDOTDIR/configs/prompt; source $ZDOTDIR/configs/hashes; print -P $LF_PROMPT')\""
    printf "%b" "\033]0;$(zsh -c 'source $ZDOTDIR/configs/prompt; source $ZDOTDIR/configs/hashes; print -P $LF_TITLE')\007" > /dev/tty
}}

cmd on-quit &printf "\033]0; $(echo $PWD | sed "s|$HOME|~|")\007" > /dev/tty

cmd paste &{{
    set -- $(cat ~/.local/share/lf/files)
    mode="$1"
    shift
    case "$mode" in
    copy)
        rsync -aP --del -- "$@" . &
        i=0
        while ps -p "$!" >/dev/null; do
            i=$(((i + 1) % 3))
            dots=""
            for i in $(seq 0 $i); do
                dots="${dots}."
            done
            lf -remote "send $id echo 'Copying$dots'"
            sleep 0.3
        done
        ;;
    move) mv -n -- "$@" . ;;
    esac
    rm ~/.local/share/lf/files
    lf -remote "send clear"
}}

cmd dupe &{{
    for file in $fx; do
        find "$PWD" "$file" -maxdepth 0 | grep -oP '(?<=.\.~)\d+(?=~$)' | sort -n | tail -1 | (
            ext=$(($(cat /dev/stdin)+1))
            filedest="$(echo "$file" | sed 's/.~[[:digit:]]*~$//').~$ext~"
            cp -r "$file" "$filedest"
        )
    done
}}

# cmd share $curl -F"file=@$fx" https://0x0.snaile.de | xclip -r -selection c

# TODO: Move this to zsh config
cmd fzfsearch ${{
    file="$(find -L $PWD | fzf --header='Searching Filenames' --preview='head -$LINES {} 2>/dev/null || ls -lhpAN --color=always --group-directories-first {}' || true)"
    [ -z "$file" ] && return
    [ -d "$file" ] && lf -remote "send $id cd $file" && return 0
    [ -f "$file" ] && lf -remote "send $id select $file"
}}
cmd fzftags ${{
    file="$(cat $XDG_DATA_HOME/lf/tags | fzf --header='Searching Tags' | sed 's/:.$//' || true)"
    [ -z "$file" ] && return
    [ -d "$file" ] && lf -remote "send $id cd $file" && return 0
    [ -f "$file" ] && lf -remote "send $id select $file"
}}
cmd fzfmarks ${{
    file="$(cat $XDG_DATA_HOME/lf/marks | fzf --header='Searching Marks' | cut -b 3- || true)"
    [ -z "$file" ] && return
    [ -d "$file" ] && lf -remote "send $id cd $file" && return 0
    [ -f "$file" ] && lf -remote "send $id select $file"
}}
cmd fzfshortcut ${{
    file="$(cat $XDG_DATA_HOME/lf/dirs | fzf --header='Searching Shortcuts' --preview='echo '{}' | cut -f2 | xargs ls' | cut -f2 )"
    [ -z "$file" ] && return
    [ -d "$file" ] && lf -remote "send $id cd $file" && return 0
    [ -f "$file" ] && lf -remote "send $id select $file"
}}
# cmd fzfworkon ${{
#     workon -n $(workon | fzf)
# }}
cmd fzfgrep ${{
    set +ue
    RG_PREFIX="rg --hidden --column --line-number --no-heading --color=always --smart-case --follow --no-ignore "
    res="$(
        FZF_DEFAULT_COMMAND="$RG_PREFIX ''" \
            fzf --bind "change:reload:$RG_PREFIX {q} || true" \
            --ansi --layout=reverse --header 'Searching file contents' |\
            grep -iv -e 'Trash/files' -e 'Trash/info'
    )"
    file="$(realpath "$(echo "$res" | cut -d':' -f1 | sed 's/\\/\\\\/g;s/"/\\"/g')" 2>/dev/null)"
    row="$(echo "$res" | cut -d':' -f2)"
    column="$(echo "$res" | cut -d':' -f3)"
    if [ -n "$res" ]; then 
        if [ -n "$VIM" ]; then
            lf -remote "send $id unselect
            send $id cd "$(dirname $file)"
            send $id set hidden
            send $id select "$file"
            send $id open
            send $id unselect"
        elif { [ "$EDITOR" = "nvim" ] || [ "$EDITOR" = "vim" ]; } && [ -n "$EMBEDDED" ]; then
            lf -remote "send $id \$$EDITOR +'call cursor($row, $column)' -- $([ -n "$EMBEDDED" ] && echo "--") '$file'"
        else
            lf -remote "send $id \$$EDITOR '$file'"
        fi
    fi
}}

cmd extract ${{
    for f in $fx; do
        aunpack "$f"
    done
}}

cmd set_previewer %{{
    if [ "${1}" = "sixel" ]; then
        lf -remote "send $id :set sixel; set previewer ~/.config/lf/preview/sixel"
        echo 'Previewer set to sixel'
    elif [ "${1}" = "ueberzug" ]; then
        lf -remote "send $id :set cleaner ~/.config/lf/preview/clean; set previewer  ~/.config/lf/preview/ueberzug"
        echo 'Previewer set to ueberzug'
    else
        lf -remote "send $id :set previewer ~/.config/lf/preview/chafa"
        echo 'Previewer set to chafa'
    fi
}}

# HACK: This is a dirty hack to have an lf terminal that I can "exit" out of into a shell
cmd new_lf_term &{{
    mapcmd='map q $sh -c "tmux; kill $id"'
    previewercmd="set_previewer $(basename "$lf_previewer")"
    $TERMINAL -e lfX -command "${previewercmd}; ${mapcmd}"
}}

&{{
    set +u
    previewer=sixel
    # [ -n "$SCRATCHPAD" ] && previewer=sixel
    [ -n "$TMUX" ] && previewer=ueberzug
    [ -n "$VIM" ] && previewer=chafa
    lf -remote "send $id set_previewer $previewer"

    # Clean up tags that don't exist anymore
    echo "$(
        while read -r l; do
            file=$(echo "$l" | cut -d ':' -f 1)
            [ -e "$file" ] && echo "$l"
        done <"${XDG_DATA_HOME}/lf/tags"
    )" >"${XDG_DATA_HOME}/lf/tags"
}}
on-cd

# Bindings
clearmaps

map <esc> quit
map <space> :toggle; down
map <enter> shell
map <a-enter> shell-wait
map <tab>a fzfsearch
map <tab>t fzftags
map <tab>m fzfmarks
map <tab>f fzfshortcut
map <tab>g fzfgrep
map "'" mark-load
map '"' mark-save
map "$" shell
map "!" shell-wait
map "&" shell-async
map ; find-next
map , find-prev
map / search 
map a :rename; cmd-home # rename from beginning
map <c-b> page-up
map b dupe
map B bulkrename
map <c-c> quit
map c push r<c-u> # new rename
map <c-d> &rm -rf -- $fx
map d cut
map <c-e> scroll-down
map e :set user_multiedit "true" ; open; set user_multiedit "false"
map E $sudo -e $f
map f find
map F find-back
map <c-g> lazygit
map <a-g> $gdu
map gg top
map g/ cd "/" 
# WARN: do not chain any more maps to g (check shortcutrc)
map G bottom
map h updir
map i :rename; cmd-end # rename from end
map j down
map k up
map l open
map m mark-save
map <c-n> push :&mkdir<space>-p<space>
map n search-next
map N search-prev
map o open-with
map O $less $f
map p paste
map P link
map q quit
map <c-r> reload
map r :rename # before extension
map R $lf -remote "send $id :select \"$(readlink $f)\""
map <c-s> set hidden!
map sn :set sortby natural; set info
map ss :set sortby size; set info size
map st :set sortby time; set info time
map sa :set sortby atime; set info atime
map sc :set sortby ctime; set info ctime
map se :set sortby ext; set info
map <c-t> $trash-restore $PWD
map t tag-toggle
map T trash
map u :clear; unselect
map <c-v> pushedit
map v invert
map W new_lf_term
map x $$f
map X !$f
map <c-y> scroll-down
map y copy
map Y &echo $f | xclip -r -selection c
map zh set hidden!
map zr set reverse!
map zn set info
map zs set info size
map zt set info time
map za set info size:time

# Load bookmark shortcuts
source "~/.config/lf/shortcutrc"