#!/bin/sh

# eslint
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM -- "*.js" "*.wxs")
if [[ "$STAGED_FILES" != "" ]]; then
  PASS=true
  echo "\nValidating Javascript:\n"
  # Check for eslint
  which eslint &> /dev/null
  if [[ "$?" == 1 ]]; then
    echo "\t\033[41mPlease install ESlint\033[0m"
    exit 1
  fi
  for FILE in $STAGED_FILES
  do
    eslint "$FILE"
    if [[ "$?" == 0 ]]; then
      echo "\t\033[32mESLint Passed: $FILE\033[0m"
    else
      echo "\t\033[41mESLint Failed: $FILE\033[0m"
      PASS=false
    fi
  done
  if ! $PASS; then
    echo "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass ESLint but do not. Please fix the ESLint errors and try again.\n"
    exit 1
  else
    echo "\033[42mESLINT SUCCEEDED\033[0m\n"
  fi
fi

# prettier
jsfiles=$(git diff --cached --name-only --diff-filter=ACM | grep ".jsx\{0,1\}$")
if [[ "$jsfiles" != "" ]]; then
  echo "\nFormatting Javascript:\n"
  FORMATE=true

  # Check for prettier
  which prettier &> /dev/null
  if [[ "$?" == 1 ]]; then
    echo "\t\033[41mPlease install prettier\033[0m"
    exit 1
  fi

  # Prettify all staged .js files
  for FILE in $jsfiles
  do
    echo "$FILE" | xargs prettier --print-width 80 --no-semi false --single-quote true --write && git add "$FILE"
    if [[ "$?" == 0 ]]; then
      echo "\t\033[32mprettier Passed: $FILE\033[0m"
    else
      echo "\t\033[41mprettier Failed: $FILE\033[0m"
      FORMATE=false
    fi
  done

  echo "\nJavascript formatting completed!\n"

  if ! $FORMATE; then
    echo "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass prettier but do not. Please fix the prettier errors and try again.\n"
    exit 1
  else
    echo "\033[42mCOMMIT SUCCEEDED\033[0m\n"
  fi
fi


exit $?