#!/bin/bash

#shellcheck disable=SC1091
#shellcheck disable=SC2155

source "$__CUSTOM_GIT_UTIL"/__intend_to_add_untracked_files
source "$__CUSTOM_GIT_UTIL"/__reset_intend_to_add_files
source "$__CUSTOM_GIT_UTIL"/fzf_headers/__gadd_header
source "$__CUSTOM_CONSOLE_UTIL"/__trim_double_quotes
source "$__CUSTOM_CONSOLE_UTIL"/__print_info
source "$__CUSTOM_CONSOLE_UTIL"/__print_err
source "$__CUSTOM_CONSOLE_UTIL"/__split_str

# ensure the command is run in a git repo
source "${__CUSTOM_GIT_UTIL}"/__assertgitrepo

__assertgitrepo

function main() {


    local numUnstagedFiles=$(git status --short | grep "^.[A-Z?] " -c)
    if [[ $numUnstagedFiles -eq 0 ]]; then
        gstatus
        echo
        __print_info "No unstaged files."
        return
    fi

    __intend_to_add_untracked_files

	local GADD_HEADER="$(__gadd_header)"

    git status --short | grep "^.[A-Z?] " |\
        fzf -m --color 'fg:160'\
            --bind 'q:abort'\
            --bind '?:toggle-preview'\
            --bind 'ctrl-r:refresh-preview'\
            --header "${GADD_HEADER}"\
            --preview "source $__CUSTOM_GIT_UTIL/fzf_previews/__gdiff_preview; __gdiff_preview {}" |\
        read_and_stage_files

    __reset_intend_to_add_files
    gstatus
}

function read_and_stage_files() {

    while read -r str; do

        if [[ ${str:0:1} != "R" ]]; then
            if [[ ${str:1:1} == " " ]]; then
                local file="${str#"${str:0:2}"}"
            else
                local file="${str#"${str:0:3}"}"
            fi
            stage_file "${file}"
            continue
        fi

        __split_str "${str}" " -> "
        local oldFile="${RESULT_ARR[0]}"
        local newFile="${RESULT_ARR[1]}"

        if [[ "${oldFile:1:1}" == " " ]]; then
            oldFile="${oldFile#"R "}"
            stage_file "${oldFile}"
        fi
        stage_file "${newFile}"
    done
}

function stage_file() {
    file="$(__trim_double_quotes "${1}")"
    git add "${file}"
}

if [[ $# -eq 0 ]]; then
    main
    exit 0
fi

if [[ $# -eq 1 && ( "$*" == "." || "$*" == "-A" ) ]]; then
    git add "$*"
    gstatus
    exit 0
fi

__print_err "valid inputs to gadd: \".\", \"-A\""