# Browser interaction utilities
browse() {
  open -na "${DEFAULT_BROWSER-}" --args "$1"
}
incognito() {
  open -na "${DEFAULT_BROWSER-}" --args --incognito "$1"
}
stackoverflow() {
  browse "https://www.google.com/search?q=site:stackoverflow.com $*"
}
github() {
  browse "https://github.com/search?q=$*"
}
bookmarks() {
  browse "https://github.com/MorganGeek/bookmarks/blob/master/README.md"
}
spotify() {
  browse "https://open.spotify.com/search/$*"
}
lob() {
  browse "https://lobste.rs"
}
vimium() {
  browse "chrome-extension://dbepggeogbaibhgnhhndojpepiihcmeb/pages/options.html#"
}

# # Prolog / Logtalk
# logtalk() {
#     path_swilgt=$(find /usr/local/Cellar/logtalk -name "*swilgt.sh" 2>/dev/null)
#     sh "$path_swilgt"
# }

# Where is a   defined?
# whichfunc() {
#     whence -v $1
#     type -a $1
# }

# source "$HOME/Code/dotfiles/dot_scripts/suggest_readable_parameters.sh"
# TODO : suggest spelling fixes

#suggest_code_refactoring() {
#    #inspired by : \grep 'awk '\''{$1=$1};1'\' $HOME/Code/dotfiles/dot_zsh*
#    header "code refactoring suggestions"
#    while read -r line; do
#    short_name=$(echo "$line" | sed -E "s/='.*//g")
#    alias_value=$(echo "$line" | sed -E 's/[a-zA-Z_-]+=//g')
#    alias_value_truncated=${alias_value:1:$((${#alias_value} - 2))}
#    \fgrep -d skip $alias_value_truncated "$@" 2>/tmp/error.log | \grep --invert-match "alias $short_name=" 1>/dev/null
#    if [ $? -eq 0 ]; then
#        success "found $short_name --> $alias_value_truncated"
#        \fgrep -d skip "$alias_value_truncated" "$@" --color -n -H --line-buffered | \grep --invert-match "alias $short_name="
#    else
#         error_message=$(\cat /tmp/error.log)
#        if [ -n "$error_message" ]; then
#            error "issue occured when looking for $alias_value_truncated : $error_message"
#        fi
#    fi
#done < <(alias | awk -v COUNT=1 'NF>COUNT') # list of all aliases, excluding the less interesting ones (where we use one word for another)
#}

# suggest_aliases() {
#     search_input_size=${1:-'50'}
#     header "alias recommendations"
#     while read -r line; do
#          matching_aliases=$(ag --multiline "$line")
#         if [ -n "$matching_aliases" ]; then
#             success "there is an alias for $line :"
#             while read -r alias_line; do
#                 arrow "$alias_line"
#             done < <(echo "$matching_aliases")
#             echo
#         else
#             warning "no alias for $line"
#         fi
#     done < <(top_commands_full "" "$search_input_size" | awk '{ $1=""; $2=""; $3="";  print}' | awk 'NF' | awk '{$1=$1};1' | awk -v COUNT=1 'NF>COUNT' H "-$search_input_size")
# }

# getabook() {
#     searchterm="$1"
# if searchbook "${searchterm}"; then
#     echo "new downloaded file"
#     grepsearchterm=$(echo "${searchterm}" | sed 's/ /.*/g')
#     if find ~/Downloads/Books -mmin -2 | grip "${grepsearchterm}.*(epub|mobi|pdf)$"; then
#             matching_file=$(find ~/Downloads/Books -mmin -2 | grip "${grepsearchterm}.*(epub|mobi|pdf)$" | head -1)
#             downloaded_file=$(basename "${matching_file}")
#         cd "${HOME}/Downloads/Books" >/dev/null 2>&1 || exit
#         success "file downloaded in your Books folder : ${downloaded_file}"
#         if file_to_kindle "${downloaded_file}" 2>/dev/null; then
#             success "file sent to your kindle, please review your emails to approve the transfer"
#             mailperso
#         else
#             error "could not send your file $downloaded_file to your email address, please check your folder"
#             open ~/Downloads/Books
#         fi
#     else
#         error "could not find a matching file in your download folder"
#     fi
# else
#     error ":'( the automatic download failed for $1, does this book exists ? check yourself or retry"
#     browse "https://libgen.lc/search.php?req=$1"
# fi
# }

# sound management
# inspired by https://apple.stackexchange.com/a/213048/231885 for switching devices
# and https://coderwall.com/p/22p0ja/set-get-osx-volume-mute-from-the-command-line for volume management
  mute_device() {
     current_device=$(SwitchAudioSource -c)
     target_device="$1"
    if SwitchAudioSource -a G "$target_device" 1>/dev/null; then
        SwitchAudioSource -s "$1" 1>/dev/null
        osascript -e 'set volume output muted true'
        success "device $target_device muted"
        SwitchAudioSource -s "$current_device" 1>/dev/null
        if [ "$current_device" != "$target_device" ]; then
            arrow "switching back to $current_device"
        fi
        arrow "currently using $current_device"
    else
        error "sound device not found : $target_device (maybe it's disconnected ?)"
    fi
}
  switch_device() {
     target_device="$1"
    if SwitchAudioSource -a G "$target_device" 1>/dev/null; then
        if SwitchAudioSource -s "$1" 1>/dev/null; then
            success "switched to $target_device"
            unmute
        else
            error "failed to switch to $target_device"
        fi
    else
        error "sound device not found : $target_device (maybe it's disconnected ?)"
    fi
}

# Web Crawling
# aboutpage() {
#   year=$(echo "$*" | grep -E --extended-regexp --only-matching '\b[[:digit:]]{4}\b' H -n1)
#   if [ -z "$year" ]; then
#       year=$(curl --silent --show-error --location "$*" | tr '<' '\r' | \grep -E --ignore-case "date|datetime" -A 1 | \grep --extended-regexp --only-matching '\b[[:digit:]]{4}\b' H -n1)
#   fi
#   author=$(curl --silent --show-error --location "$*" | tr '<' '\r' | \grep -E --ignore-case "author" -A 1 | \grep --extended-regexp --only-matching '([A-Z][A-Za-z]+\s([A-Za-z ]+)*)' H -n1)
#   title=$(curl --silent -SL "$*" | tr '<' '<\n' | \grep title -A 1 H -n1 | sed -E 's/.*<title>(.*)<\/title>.*/\1/' | sed "s/ [^[:alnum:]]*$author//")
#   yearint=$((year + 0))
#   currentyear="$(date +"%Y")"
#   if [ -n "$author" ]; then
#       echo "by $author"
#   fi
#   if [ -n "$title" ]; then
#       echo "-> $title"
#   fi
#   if [ "$yearint" -ge 1970 ] && [ "$yearint" -le "$currentyear" ]; then
#       echo "$yearint"
#   fi
#   if [ ! -z "$title" ] && [ ! -z "$author" ] && [ $yearint -ge 1970 ] && [ $yearint -le $currentyear ]; then
#       echo "[$author]($*) - ($yearint) $title"
#   fi
# }

# Code search / stats helpers
cmd_loc="find . -type f \( \
        -name '*.py' \
        -o -name '*.rb' \
        -o -name '*.go' \
        -o -name '*.java' \
        -o -name '*.kt' \
        -o -name '*.c' -o -name '*.h' \
        -o -name '*.js' \
        -o -name '*.tsx' \
        -o -name '*.sh' \
        -o -name '*.md' \
        -o -name '*.xml' \
        -o -name '*.yaml' -o -name '*.yml' \
        -o -name '*.groovy' \
        -o -name '*.gradle' \
        -o -name '*.properties' \
        \) -exec \cat \{\} \; | LANG=C LC_CTYPE=C sed -e 's/^[ \t]*//;s/[ \t]*$//'"

# Unique lines of code
# Via https://text.causal.agency/004-uloc.txt
  uloc() {
    eval "$cmd_loc | LANG=C LC_CTYPE=C sort --unique | wc -l"
}
# Top lines of code
  toploc() {
    eval "$cmd_loc | LANG=C LC_CTYPE=C cut -c 1-100 | LANG=C LC_CTYPE=C sort | uniq -c | LANG=C LC_CTYPE=C sort --numeric-sort --reverse H -50"
}
  historyloc() {
    top_commands_full "" 5000 topshellloc
}
  how_in() {
    where="$1"
    shift
    IFS=+ curl "cht.sh/${where}/$*"
}
# File name references in file
filerefs() {
FILENAME=${1:-README*)}
\grep --extended-regexp --only-matching "\b([a-zA-Z.-]+)\.([a-z]{2,4}\b)" "$FILENAME" \
    | sort --unique \
    | grep -E --invert-match --ignore-case "\.com|\.git|\.io|\net|\.org|\.se|\.me|\.fr|contributing\.md"
}
# invalid_file_refs() {
# FILENAME=${1:-"README.*"}
# while read -r file_ref; do
#     arrow "processing $file_ref ..."
#     find . -name "$file_ref" 1>/dev/null
#         exit_status=$?
#     if [ "$exit_status" -eq 1 ]; then
#         warning "$file_ref does not exist in the project"
#     else
#         success "$file_ref was found in the project"
#     fi
#     arrow "checking if $file_ref is present in the source code..."
#     source_refs=$(\grep "$file_ref" * -r -l G --invert-match "$FILENAME" | wc -l 2>/dev/null | trim)
#     if [ "$source_refs" -eq 0 ]; then
#         error "$file_ref was not found in source code"
#     else
#         arrow "searching for $file_ref references in soure code..."
#         while read -r source_ref; do
#             success "$file_ref was found in $source_ref"
#         done < <(\grep "$file_ref" * -r -l)
#     fi
# done < <(filerefs "$FILENAME")
# }


# Text search
# run write-good, proselint, and aspell in non interactive mode, to list all mispelled words found
  checkenlist() {
    aspell -d en list < "$1" | sort --unique --ignore-case
    write-good --no-passive "$1"
    proselint "$1"
    alex -q --stdin < "$1"
}

# checkenremote() {
#     target_url="$1"
# if [[ ! "$target_url" =~ "githubusercontent.com" && ! "$target_url" =~ "README" && ! "$target_url" =~ "readme" ]]; then
#     arrow "no readme found"
#         guess_readme_url=$(http "$target_url" | \grep -ioP 'href="\K.*REAdme.(md|rst)(?=")' | head -1)
#     arrow "does https://github.com${guess_readme_url} exist "
#     arrow "guess url : $guess_readme_url"
#     if http --check-status "https://github.com${guess_readme_url}" &>/dev/null; then
#         target_url="https://github.com${guess_readme_url}"
#         arrow "target url changed to ${target_url}"
#     else
#         arrow "https://github.com${guess_readme_url} do not exist"
#     fi
# fi
# target_url=$(echo "$target_url" | sed 's/github.com/raw.githubusercontent.com/g' | sed 's;blob/;;')
# arrow "checking $target_url"
# curl --location --insecure --silent "$target_url" > /tmp/file && checkenlist /tmp/file #&& write-good --no-passive /tmp/file && proselint /tmp/file && \cat /tmp/file > alex -q --stdin
# }

# File stats helpers
# Find files bigger than X size and sort them by size
  biggerthan() {
    find . -size "+$*" -type f -print0 | xargs -0 ls -Ssh | sort --zero-terminated
}
# To automatically ls when changing directory
  cd() {
    builtin cd "$@" && ll -atr
}

# Conversion
  epub2pdf() {
     output_file_name=$(echo "$1" | sed 's/.epub$/.pdf/')
    ebook-convert "$1" "${output_file_name}"
}
  epub2mobi() {
     output_file_name=$(echo "$1" | sed 's/.epub$/.mobi/')
    ebook-convert "$1" "${output_file_name}"
}

# Uploaders
  transfer() {
    # check arguments
    if [ $# -eq 0 ]; then
        warning "No arguments specified. Usage:\necho transfer /tmp/test.md\ncat /tmp/test.md | transfer test.md"
        return 1
    fi

    # get temporarily filename, output is written to this file show progress can be showed
    tmpfile=$(mktemp -t transferXXX)

    # upload stdin or file
    file=$1

    if tty -s; then
        basefile=$(basename "$file" | sed -e 's/[^a-zA-Z0-9._-]/-/g')

        if [ ! -e "$file" ]; then
            error "File $file doesn't exists."
            return 1
        fi

        if [ -d "$file" ]; then
            # zip directory and transfer
            zipfile=$(mktemp -t transferXXX.zip)
            cd "$(dirname "$file")" && zip -r -q - "$(basename "$file")" >>"$zipfile"
            curl --progress-bar --upload-file "$zipfile" "https://transfer.sh/$basefile.zip" >>"$tmpfile"
            rm -f "$zipfile"
        else
            # transfer file
            curl --progress-bar --upload-file "$file" "https://transfer.sh/$basefile" >>"$tmpfile"
        fi
    else
        # transfer pipe
        curl --progress-bar --upload-file "-" "https://transfer.sh/$file" >>"$tmpfile"
    fi
    # cat output link
    cat "$tmpfile"

    # cleanup
    rm -f "$tmpfile"
}

  # checkov() { docker run -i --rm -v "$(pwd):/tf" bridgecrew/checkov -d /tf "$@"; }
  vimat() {
    vim +/"$1" "$2"
}
  httperr() {
    curl --silent "https://http.cat/$1" | imgcat
}

# Security / Secrets helpers
  passwords() {
    bw list items --search "$1" | jq -c '.[] | .name + " " + .login.username + ":" + .login.password + " " +  .login.uris[0].uri'
}
  password() {
    bw get password "$1"
}
  vaultgetsecret() {
     secret=$(grep -A 500 "ANSIBLE_VAULT" "$1" | awk '{$1=$1;print}' | \grep --extended-regexp --only-matching "^[0-9a-z^ ]+$")
     secret_string=$(echo "\$ANSIBLE_VAULT;1.1;AES256\n$secret")
    echo "$secret_string" | awk '{$1=$1;print}' | ansible-vault decrypt --vault-password-file=$VAULT_PASSWORD_FILE
}

### Git helpers
  backupgithub() {
    cd "$REPO_PATH"
    curl --silent --location "https://api.github.com/users/$1/repos" | jq -r '.[] | .ssh_url' | xargs -n1 git clone --mirror --no-hardlinks
}
  gitydiff() {
     path_to_file="$1"
    gsh "HEAD:$path_to_file" | colordiff -y - "$path_to_file"
}
  gcrb() {
    branch=$1
    gcb $branch origin/$branch
}

  installhooks() {
    pre-commit install --install-hooks --overwrite --allow-missing-config
}
  copyhooks() {
    FILENAME=${1:-"$HOME/.git-template/.pre-commit-config.yaml"}
    cp -f "$FILENAME" ./.pre-commit-config.yaml
    installhooks
    runhooks
}
  git_listobjectsbysize() {
    tempFile=$(mktemp)
    IFS=$'\n'
    for commitSHA1 in $(git rev-list --all); do
        git ls-tree -r --long "$commitSHA1" >>"$tempFile"
    done

    # sort files by SHA1, de-dupe list and finally re-sort by filesize
    sort --key 3 "$tempFile" |
        uniq |
        sort --key 4 --numeric-sort --reverse
    # remove temp file
    rm -f "$tempFile"
}
  setorigin() {
    gra origin "$1" 2>/dev/null
    grset origin "$1"
    success "updated origin to $1"
    arrow "copying pre-commit hooks ..."
    if [[ "$1" =~ "$COMPANY_NAME" ]]; then
        copyhooks
        gitpro
    else
        copyhooks "$HOME/.git-template/.pre-commit-minimal-config.yaml"
        gitperso
    fi
}
  gitpushcurrentremote() {
    gitpushallremote "$(git_current_branch)"
}
  gitpushallremote() {
     param_branch="$1"
    grv
    grv G push | awk '{print $1}' | while read -r remote; do
        if [ -z "$param_branch" ]; then
            arrow "pushing all branches to $remote"
            gp --all "$remote"
        else
            arrow "pushing $param_branch to $remote"
            gp "$remote" "$param_branch"
        fi
    done
}
  clone() {
     folder=$(basename $1 | sed 's/\.git.*//g')
    arrow "git project identified as $folder"
    arrow "cloning repository ..."
    if gcls "$1"; then
        success "repository cloned"
        if [[ -n "$folder" ]]; then
            cd "$folder" || exit
            arrow "copying pre-commit hooks ..."
            if [[ "$1:u" =~ "$COMPANY_NAME:u" ]]; then
                copyhooks
                gitpro
            else
                copyhooks "$HOME/.git-template/.pre-commit-minimal-config.yaml"
                gitperso
            fi
        else
            error "unable to change current directory to : $folder"
        fi
    else
        error "unable to clone repository from url : $1"
    fi
}
  fork() {
    code || exit
     folder=$(basename $1 | sed 's/\.git.*//g')
    gh repo fork "$1" --clone && cd "$folder"
    if [[ "$1:u" =~ "$COMPANY_NAME:u" ]]; then
        gitpro
    else
        gitperso
    fi
    checkreadme
    # TODO : check all the codebase for spelling mistakes in info/debug/error messages etc.
}
  git-project() {
    if [ -d "$REPO_PATH" ]; then
        REPO_PATH="$(pwd)"
    fi
     preview='lsd --color always --icon always --group-dirs first {}'
     dir=$(find "$REPO_PATH" -maxdepth 3 -type d -name ".git" | sed 's#.git$##' | fzf --select-1 --query="$*" --preview "$preview")
    if [[ -n "$dir" ]]; then
        cd "$dir" || exit
    fi
}
  gitignorefor() {
     language=${1:-''}
    if [ ! -d "$HOME/Code/gitignore" ]; then
        arrow "cloning https://github.com/github/gitignore into $REPO_PATH/gitignore"
        git clone "https://github.com/github/gitignore $_"
    fi
     gitignore_file=$(fd "$language" "$REPO_PATH/gitignore" H -n1)
    if [ ! -z "$gitignore_file" ]; then
        success "matched gitignore file : $gitignore_file"
        if [ ! -f "$(pwd)/.gitignore" ]; then
            arrow "you don't have a $(pwd)/.gitignore file, but that's not an issue :-) ..."
        fi
        arrow "copying the file content to your $(pwd)/.gitignore file"
        adhoc blockinfile -a "block='{{ lookup('file', '$gitignore_file') }}' dest='$(pwd)/.gitignore' create=yes"
    else
        error "no gitignore file found for $language"
    fi
}

# Miscellaneous helpers
bookmarkadd() {
  adhoc lineinfile -a "path=$HOME/Code/bookmarks/README.md insertafter='"$1"' line='* "$2"'"
}
rssadd() {
  adhoc lineinfile -a "path=~/.config/newsboat/urls line='"$1"'"
  newsboat
}

# Via https://stackoverflow.com/a/58598185/2309958
# capture the output of a command so it can be retrieved with ret
  cap () { tee /tmp/capture.out; }
# return the output of the most recent command that was captured by cap
  ret () { \cat /tmp/capture.out; }

# Make a directory and cd to it
  take() {
    md -p "$@" && cd "${@:$#}"
}

  file_dups() {
    \cat "$1" | sort_count
}
  foreach_run() {
    find . -name "$1" -exec "$2" {} \;
}
# input should be something like : 1-10 to generate one number between 1 and 10
  chance() {
    [[ $(shuf -i "$1" -n 1) == 1 ]]
}
