# vim:set ft=zsh

# LF Change Dir
function lfcd () {
    tmp="$(mktemp)"
    fid="$(mktemp)"
    lf -command '$printf $id > '"$fid"'' -last-dir-path="$tmp" "$@"
    id="$(cat "$fid")"
    archivemount_dir="/tmp/__lf_archivemount_$id"
    if [ -f "$archivemount_dir" ]; then
        cat "$archivemount_dir" | \
            while read -r line; do
                sudo umount "$line"
                rmdir "$line"
            done
        command rm -f "$archivemount_dir"
    fi
    if [ -f "$tmp" ]; then
        dir="$(cat "$tmp")"
        command rm -f "$tmp"
        if [ -d "$dir" ]; then
            if [ "$dir" != "$(pwd)" ]; then
                cd "$dir"
            fi
        fi
    fi
    tput cuu1;tput el
}
function _lfcd () {
  BUFFER="lfcd"
  zle accept-line
}
zle -N _lfcd

# Cursor Shape
function zle-keymap-select () {
    case $KEYMAP in
        vicmd) echo -ne '\e[1 q';;      # block
        viins|main) echo -ne '\e[5 q';; # beam
    esac
}
zle -N zle-keymap-select
zle-line-init() {
    zle -K viins # initiate `vi insert` as keymap (can be removed if `bindkey -V` has been set elsewhere)
    echo -ne "\e[5 q"
}
zle -N zle-line-init

# CMDLine Edit
zle -N edit-command-line

# Lazygit
function lg () {
  [ ! -d "$(pwd)/.git" ] && [[ $(read -ek "?Not in a git repository. Create a new git repository? (y/n): ") =~ ^[Yy]$ ]] && git init
  [ -d "$(pwd)/.git" ] && lazygit -p $(pwd)
  zle reset-prompt
}
zle -N lg{,}