# Functions
cmd open ${{
    set +u
    files=${@:-$fx}
    [ "$lf_user_multiedit" = "true" ] && {
        $EDITOR $fx
        lf -remote "send $id unselect"
        return
    }
    $OPENER "$f"
}}

cmd pushedit %{{
    set +u
    files=$1
    [ -z $files ] && {
        echo "Open: " && read -r files
        echo
    }
    echo $files | xargs -r touch
    lf -remote "send $id \$$OPENER $files"
}}

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"
}}

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
        copy) ln -sr -t . -- "$@";;
        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 fzf ${{
    name="$1" input="$2" delimiter="$3" field="$4" path_field="$5" width="$6" query="${7:-}"
    histfile="$XDG_DATA_HOME/lf/$(echo $name | tr '[:upper:]' '[:lower:]')_history"

    clear
    file="$(eval "$input" | fzf \
        --query "$query" \
        --delimiter "$delimiter" \
        --cycle \
        --nth="$field" \
        --with-nth="$field" \
        --preview-window="right,$width" \
        --bind="space:accept,focus:transform-preview-label(echo {} | cut -d '$delimiter' -f '$path_field')" \
        --scheme='history' \
        --history="$histfile" \
        --header="$name" \
        --preview='
            file=$(echo {} | cut -d '$delimiter' -f '$path_field')
            if [ -f "$file" ] && [ -r "$file" ]; then
                head -$LINES "$file"
            elif [ -d "$file" ] && [ -r "$file" ]; then
                ls -pLHAN1 --color=always --group-directories-first "$file"
            fi
        ' |
        cut -d "$delimiter" -f "$path_field" |
        tr -d '\n'
    )"
    [ -d "$file" ] && lf -remote "send $id cd $file"
    [ -f "$file" ] && lf -remote "send $id select $file"
    return 0
}}

cmd find_word ${{
    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 { [ "$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
    return 0
}}

cmd find_project ${{
    dirs=$(echo $XDG_DOCUMENTS_DIR/dev/*/*)
    histfile="$XDG_DATA_HOME/lf/project_history"

    clear
    project="$(echo $dirs | xargs -n1 basename | fzf \
        --cycle \
        --preview-window="right,33%" \
        --bind="space:accept,focus:transform-preview-label(echo {})" \
        --scheme='history' \
        --history="$histfile" \
        --header="Projects" \
        --preview='
            f={}
            file=$(echo $XDG_DOCUMENTS_DIR/dev/*/* | xargs -n1 | sed -n "/\/$f$/p")
            if [ -f "$file" ] && [ -r "$file" ]; then
                head -$LINES "$file"
            elif [ -d "$file" ] && [ -r "$file" ]; then
                ls -pLHAN1 --color=always --group-directories-first "$file"
            fi
        ' |
        tr -d '\n'
    )"
    file=$(echo $dirs | xargs -n1 | sed -n "/\/$project$/p")
    [ -d "$file" ] && lf -remote "send $id cd $file"
    [ -f "$file" ] && lf -remote "send $id select $file"
    return 0
}}

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

# 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"'
    $TERMINAL -e lfX -command "$mapcmd"
}}

on-cd

# 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
set sixel
set previewer ~/.config/lf/preview/preview
set cleaner ~/.config/lf/preview/clean

# Bindings
clearmaps

map <esc> quit
map <space> :toggle; down
map <enter> shell
map <a-enter> shell-wait
map <tab><tab> find_project
map <tab>t fzf 'Tags' 'cat $XDG_DATA_HOME/lf/tags 2>/dev/null' ':' '1' '1' '50%'
map <tab>m fzf 'Marks' 'cat $XDG_DATA_HOME/lf/marks 2>/dev/null' ':' '1' '2' '85%' '^'
map <tab>f fzf 'Files' 'find -L $PWD' ':' '1' '1' '50%'
map <tab>g find_word
map "'" mark-load
map '"' mark-remove
map "$" shell
map "!" shell-wait
map "&" shell-async
map ";" find-next
map "," find-prev
map "/" search 
map a :rename; cmd-end # rename from end
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 /
# NOTE: g* is used for shortcuts generated by the shortcuts script
source ~/.config/lf/shortcuts
map G bottom
map h updir
map i :rename; cmd-home # rename from beginning
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 sh :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