#!/usr/bin/env sh

if ! exist git-bug; then
    return 1
fi

# POSIX-compliant version of . <(cmd) substitution
# shellcheck source=/dev/null # but shellcheck can't access
git-bug completion zsh | . /dev/fd/0

alias gbt='git-bug termui'
gb() {
    if [ "$#" -eq 1 ] && git-bug bug status "$1" >/dev/null 2>/dev/null; then
        git-bug bug show "$1"
    else
        git-bug bug "$@"
    fi
}
alias gbw="git-bug bug show"
alias gbs="git-bug bug select"

alias gbn='git-bug bug new'
alias gbm='git-bug bug comment new'

# 'git-bug edit' function to edit:
#   - bug descriptions (pass a bug-id)
#   - comments (pass a comment-id)
if [ -x "$(command -v vipe)" ] && [ -x "$(command -v jq)" ]; then
    gbe() {
        if git-bug bug status "$1" >/dev/null 2>/dev/null; then
            id=$(git-bug bug show --format json "$1" | jq --raw-output '.comments[0].id')
            msg=$(git-bug bug show --format json "$1" | jq --raw-output '.comments[0].message')
            chain=$(git-bug bug show "$1" | while read -r line; do echo "# $line"; done)

            txt="$(printf "%s\n\n%s\n# %s" "$msg" "# Please enter the comment message. Lines starting with '#' will be ignored,
# and an empty message aborts the operation.
#
# Bug history:
#" "$chain")"

            outp=$(printf "%s" "$txt" | vipe | sed '/^#/d')
            comp=$(printf "%s" "$txt" | sed '/^#/d')
            if [ -z "$outp" ]; then
                echo Empty message, nothing to do. >&2
            elif [ "$comp" = "$outp" ]; then
                echo No change detected, nothing to do. >&2
            else
                git-bug bug comment edit -m "$outp" "$id"
            fi
        else
            # TODO: Populate comment edit msg with old comment just like above
            # Might need upstream changes to have 'show bug comment' interface
            # because currently we can't just 'display' a single bug comment
            # TODO: If git-bug has a bug selected (with git-bug select)
            # we could use this here
            git-bug bug comment edit "$@"
        fi
    }
fi

# TODO: edit bug title
alias gbte='git-bug bug title edit'

# TODO: Implement toggle function
# grab current status and then open or close accordingly
alias gbo='git-bug bug status close'

alias gbp='git-bug push'
alias gbl='git-bug pull'

alias gbu='git-bug user' # list users
# show primary user info
alias gbU='git-bug user user "$(git-bug user | cut -d" " -f1 | head -n1)"'