#!/bin/sh
#
#
JSONRESOURCE=https://raw.githubusercontent.com/commitizen/conventional-commit-types/master/index.json
BCKJSONRESOURCE=https://raw.githubusercontent.com/cdcabrera/bash-gitcommitizen/master/src/types.json
declare -a TYPEDESCRIPTIONS
declare -a TYPEKEYS
#
# Parse JSON through node
#
setTypes()
{
  JSON=$(curl -sf $JSONRESOURCE)

  if [ -z "$JSON" ]; then
    JSON=$(curl -sf $BCKJSONRESOURCE)

    if [ -z "$JSON" ]; then
      echo Commit types JSON failed to load.
      exit 0
    fi
  fi

  DESCS=$(node -pe '(function(){const arr=[]; let j={}; try{j=JSON.parse(process.argv[1]).types}catch(e){}; Object.keys(j).forEach(function(value, index){arr.push("  "+(index+1)+") "+value+" \t- "+j[value].description)}); return arr.join("~");})()' "$JSON")
  KEYS=$(node -pe 'try{(Object.keys(JSON.parse(process.argv[1]).types)).join("~")}catch(e){}' "$JSON")

  if [ "$KEYS" = "undefined" ]; then
    echo Commit types JSON failed to parse.
    exit 0
  fi

  TYPEKEYS=(${KEYS//\~/ })
  IFS='~' read -a TYPEDESCRIPTIONS <<< "$DESCS"
}
#
# Display types with descriptions
#
displayTypes()
{
  echo
  echo Types:

  for type in "${TYPEDESCRIPTIONS[@]}"
  do
    echo "$type"
  done

  echo
  echo Choose commit type:
}
#
#
# main()
#
{
  STEPS=1
  CT=0
  CTDISPLAY=""
  TITLE=""
  DESC=""
  DETAILEDDESC=""

  setTypes

  exec < /dev/tty

  while true; do

    case "$STEPS" in
      1) read -p "$(displayTypes) " CT;;
      2) read -p "Enter a title: " TITLE;;
      3) read -p "Enter brief description: " DESC;;
      4) read -p "Enter a detailed description: " DETAILEDDESC;;
    esac

    if [ "$CT" = "q" ] || [ "$TITLE" = "q" ] || [ "$DESC" = "q" ] || [ "$DETAILEDDESC" = "q" ]; then
        exit 1;
    fi

    if [ "$CT" = "s" ] || [ "$TITLE" = "s" ] || [ "$DESC" = "s" ] || [ "$DETAILEDDESC" = "s" ]; then
        exit 0;
    fi

    if [[ $CT -ge 1 && $CT -le ${#TYPEKEYS[@]} ]]; then
      CTDISPLAY="${TYPEKEYS[$((CT-1))]}"

      if [ ! -z "$CTDISPLAY" ]; then
        STEPS=2
      fi
    fi

    if [ ! -z "$TITLE" ]; then
      STEPS=3
    fi

    if [ ! -z "$DESC" ]; then
      STEPS=4
    fi

    if [ ! -z "$DETAILEDDESC" ]; then
      echo "# $CTDISPLAY($TITLE): $DESC\n# $DETAILEDDESC" | cat - $1 > temp && mv temp $1
      exit 0;
    fi

  done
}
