# 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 &{{
    trash-util put $fx
    lf -remote "send load"
}}

cmd trash-restore ${{
    fileid=$(
        trash-util list "$PWD" |
            fzf -d '\0' \
                --with-nth=1 \
                --nth=1 \
                --preview='printf "Original path: %s\nInfo path:     %s\nTrashed on:    %s\n" {1} {2} {3}' |
            cut -d '' -f 2
    )
    [ -z "$fileid" ] && exit
    trash-util restore $fileid
}}

cmd lazygit ${{
    dir=$(dirname "$(realpath "${f:-_}")"})
    if git --noglob-pathspecs -C $dir status >/dev/null 2>&1; then
        lf -remote "send $id \$cd '$dir' && lazygit"
    else
        lazygit -p "$STOW_DIR/$DOTS_PACKAGE"
    fi
}}

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 \
        --exact \
        --query "$query" \
        --delimiter "$delimiter" \
        --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 -n $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"
for cmd in bat batcat head; do
    command -v $cmd >/dev/null 2>&1 && break
done
res="$(
    FZF_DEFAULT_COMMAND="$RG_PREFIX ." SEDPATTERN='s/\\/\\\\/g;s/"/\\"/g' SHELL="sh" \
        fzf \
        --ansi \
        --exact \
        --bind "change:reload:${RG_PREFIX} {q} || true" \
        --preview-window="right,50%" \
        --preview="
            file=\$(realpath \"\$(echo {} | cut -d: -f1 | sed \"\${SEDPATTERN}\")\" 2>/dev/null)
            case '$cmd' in
                head) head -n 300 \"\$file\" ;;
                bat*) '$cmd' --color=always --italic-text=always --style=plain --pager=never \
                    --tabs=4 --theme=base16 --line-range :300 \"\$file\" ;;
            esac
        " \
        --layout=reverse \
        --header 'Searching file contents'
)"
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" ]; then
        lf -remote "send $id \$$EDITOR +'call cursor($row, $column)' -- '$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 \
        --preview-window="right,50%" \
        --bind="space:accept,focus:transform-preview-label(echo {})" \
        --scheme='history' \
        --history="$histfile" \
        --header="Projects" \
        --preview='
            f={}
            dir=$(echo $XDG_DOCUMENTS_DIR/dev/*/* | xargs -n1 | sed -n "/\/$f$/p")
            git -C $dir status
            echo
            git -C $dir log
        ' |
        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"
}}

cmd confirm_delete %{{
    echo Delete? [y/N] && read -r v
    echo
    [ "$v" = y ] && rm -rf -- $fx
}}

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' 'fd -L --full-path $PWD' ':' '1' '1' '50%'
map <tab>g find_word
map "'" mark-load
map '"' mark-remove
map "$" shell
map "!" shell-wait
map "&" shell-async
map "%" shell-pipe
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> confirm_delete
map d cut
map D &dragon-drop -a -x $fx
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
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