# vim: ft=sh:fdl=0:noml:
#                 ██              ████          ████
#                ░██             ░██░          ░██░
#  ██████  ██████░██            ██████ ██████ ██████
# ░░░░██  ██░░░░ ░██████  █████░░░██░ ░░░░██ ░░░██░
#    ██  ░░█████ ░██░░░██░░░░░   ░██     ██    ░██
#   ██    ░░░░░██░██  ░██        ░██    ██     ░██
#  ██████ ██████ ░██  ░██        ░██   ██████  ░██
# ░░░░░░ ░░░░░░  ░░   ░░         ░░   ░░░░░░   ░░
#
#  ~/.zshrc
#  ~/.zsh-local
#
#
#  TODO: Ideas on how an ideal fzf-based shell should work for me
#       - DONE: fl: fuzzy locate any file/folder. File => open with peek, folder => cd
#       - TODO: fh: same as fuzzy locate, but in the current directory
#       - No app should require an argument, just like fl works

# ZSH_CACHE_DIR=~/.cache
fzf_history_widget_accept() {
  fzf-history-widget
  zle accept-line
}
zle -N fzf_history_widget_accept
bindkey '^X^R' fzf_history_widget_accept
# bindkey '^R' fzf-history-widget

# if [ -x "$(command -v rg)" ]; then
#   export FZF_DEFAULT_COMMAND='rg --files --no-ignore --hidden --follow -g "!{.git,node_modules}/*" -g "!*.o" 2> /dev/null'
# elif [ -x "$(command -v fd)" ]; then
#   export FZF_DEFAULT_COMMAND='fd --hidden --follow --exclude .git'
# else
#   export FZF_DEFAULT_COMMAND='find . -path ./.dropbox-dist -prune -o -printf "%P\\n"'
# fi

#export FZF_CTRL_T_COMMAND='find . -path ./.dropbox-dist -prune -o -printf "%P\\n"'
export FZF_CTRL_T_COMMAND='fd -t f'
export FZF_ALT_C_COMMAND='fd -t d'
export FZF_DEFAULT_OPTS="--preview-window wrap --bind 'ctrl-v:toggle,ctrl-s:toggle+down,ctrl-n:down,ctrl-p:up,ctrl-x:execute@nohup xdg-open {} >/dev/null 2>&1 & disown@,ctrl-e:execute@nohup litepub {} >/dev/null 2>&1 & disown@','ctrl-r:execute@frifle {}@','alt-j:half-page-down','alt-k:half-page-up','ctrl-f:jump' --color='bg+:#5E81AC,prompt:#EBCB8B' --reverse"

# if [ -x "$(command -v fd)" ]; then
#   # Use fd (https://github.com/sharkdp/fd) instead of the default find
#   # command for listing path candidates.
#   # - The first argument to the function ($1) is the base path to start traversal
#   # - See the source code (completion.{bash,zsh}) for the details.
#   _fzf_compgen_path() {
#     fd --hidden --follow --exclude ".git" . "$1"
#   }
#
#   # Use fd to generate the list for directory completion
#   _fzf_compgen_dir() {
#     fd --type d --hidden --follow --exclude ".git" . "$1"
#   }
# fi

# vg: persistent fuzzy grep-edit via rg/ag/grep {{{
vg() {
  # TODO: instead of grepping the line in preview, use line number
  if [ "$#" -eq 0 ]; then
    echo "Need a string to search for!"
    return 1
  fi
  if command -v rg >/dev/null 2>&1; then
    rg -S --no-heading --no-messages --line-number "$@" | fzf -e -d ':' --preview 'rg --ignore-case --pretty --with-filename --context 10 -F '"{3..}"' {1}' --bind "enter:execute: $EDITOR {1} +{2}"
  elif command -v ag >/dev/null 2>&1; then
    ag -S --nobreak --noheading "$@" | fzf -e -d ':' --bind "enter:execute: $EDITOR {1} +{2}"
  else
    grep -irE "$@" | fzf -e -d ':' --bind "enter:execute: $EDITOR {1} +{2}"
  fi
}

#}}}

# dj - jump to selected directory {{{
dj() {
  dir=$(find "${1:-.}" -path '*/\.*' -prune \
    -o -type d -print 2>/dev/null | fzf +m) \
    && cd "${dir}" || return
}

# dja - including hidden directories
dja() {
  dir=$(find "${1:-.}" -type d 2>/dev/null | fzf +m) \
    && cd "${dir}" || return
}
#}}}

# GIT {{{
#
# fshow - git commit browser

alias glNoGraph='git log --color=always --format="%C(auto)%h%d %s %C(cyan)%C(bold)%cr% C(auto)%an"' # "$@"
_gitLogLineToHash="echo {} | grep -o '[a-f0-9]\{7\}' | head -1"
_viewGitLogLine="${_gitLogLineToHash} | xargs -I % sh -c 'git show --color=always % | less '"

fshow() {
  git log --graph --color=always \
    --format="%C(auto)%h%d %s %C(cyan)%C(bold)%cr" "$@" \
    | fzf --ansi --no-sort --reverse --tiebreak=index --bind=ctrl-s:toggle-sort \
      --header "enter to view, ctrl-y to copy hash" \
      --bind "ctrl-y:execute:${_gitLogLineToHash} | xclip -i -selection clipboard" \
      --bind "ctrl-m:execute:
    (grep -o '[a-f0-9]\{7\}' | head -1 \
      | xargs -I % sh -c 'git show --color=always % | less -R') << 'FZF-EOF'
{}
FZF-EOF"
}

# fshow_preview - git commit browser with previews
fshow_preview() {
  glNoGraph \
    | fzf --no-sort --reverse --tiebreak=index --no-multi \
      --ansi --preview="${_viewGitLogLine}" \
      --header "enter to view, ctrl-y to copy hash" \
      --bind "enter:execute:${_viewGitLogLine}   | less -R" \
      --bind "ctrl-y:execute:${_gitLogLineToHash} | xclip -i -selection clipboard"
}

#}}}

# Autojump: {{{
j() {
  if [ ! -x "$(command -v autojump)" ]; then
    fj
    return
  fi

  if [ "$#" -ne 0 ]; then
    cd $(autojump $@)
    return
  fi
  cd "$(autojump -s | sed '/_____/Q; s/^[0-9,.:]*\s*//' | fzf --height 40% --reverse --inline-info)"
}

k() {
  if [ ! -x "$(command -v zoxide)" ]; then
    fj
    return
  fi

  if [ "$#" -ne 0 ]; then
    cd $(__zoxide_z $@)
    return
  fi
  cd "$(zoxide query --list --score | sed 's/^\s*[0-9,.:]*\s*//' | fzf --height 40% --reverse --inline-info)"
}
#}}}

# p: {{{
p() {
  open=xdg-open # this will open pdf file withthe default PDF viewer on KDE, xfce, LXDE and perhaps on other desktops.

  ag -U -g ".pdf$" \
    | fast-p \
    | fzf --read0 --reverse -e -d $'\t' \
      --preview-window down:80% --preview '
            v=$(echo {q} | tr " " "|");
            echo -e {1}"\n"{2} | grep -E "^|$v" -i --color=always;
        ' \
    | cut -z -f 1 -d $'\t' | tr -d '\n' | xargs -r --null $open >/dev/null 2>/dev/null
}

#}}}

# FSH / Fuzzy SSH: {{{
fsh() {
  ssh -Y "$(grep '^Host\b' $HOME/.ssh/config* | awk '{print $2}' | fzf -q "$1" -1)"
}

fst() {
  grep '^Host\b' $HOME/.ssh/config* | awk '{print $2}' | fzf -m -q "$1" -1 | while read host; do
    ssh -O stop "$host"
  done
}

#}}}

# fsend:{{{
fsend() {
  # TODO: Allow depth=1 for home dir
  # TODO: Fix for files with spaces
  BAK="$FZF_DEFAULT_COMMAND"
  # export FZF_DEFAULT_COMMAND='find . -path ./.dropbox-dist -prune -o -printf "%P\\n"'
  export FZF_DEFAULT_COMMAND='fd .'

  files=$(fzf -m --reverse -q "$1")
  [ -z "$files" ] && return

  host=$(grep '^Host\b' $HOME/.ssh/config* | awk '{print $2}' | fzf)
  [ -z "$host" ] && return

  host=$host":sent"

  while IFS='\n' read -r file; do
    scp -rC "$file" "$host"
  done <<<"$files"

  export FZF_DEFAULT_COMMAND="$BAK"
}

# }}}

# fkill: {{{
fkill() {
  pid=$(ps -ef \
    | sed 1d \
    | fzf -m --preview="ps -p {2}" --preview-window=down:3 \
    | awk '{print $2}')

  if [ "x$pid" != "x" ]; then
    kill -"${1:-9}" "$pid"
  fi
}
# }}}
