#!/usr/local/bin/bash
declare -A _moduleEntryFile

_pwd="$(pwd)/diffs"
_configPath="$(pwd)/.marioconfig"

_moduleName=$3

function generateBundle
{
  react-native bundle --entry-file $1 --bundle-output $2/index.bundle --platform $3 --assets-dest $2 --dev false
}

while read line;do
  eval "$line"
done < $_configPath

_targetPlatformPath="$_pwd/$_platform"
_targetLocal="$_pwd/$_platform/$_local"
_targetRemote="$_pwd/$_platform/$_remote"
_targetModule="$_pwd/$_platform/$_moduleName"
_targetModuleLocal="$_targetModule/$_local"
_targetModuleRemote="$_targetModule/$_remote"

for moduleName in ${_modules[*]}; do
  _moduleEntryFile+=([$moduleName]="$_modulePath/$moduleName/$_entryFile")
done

if [[ $3 ]]; then
  if [[ ${_moduleEntryFile[$_moduleName]} ]]; then
    _entryFile=${_moduleEntryFile[$_moduleName]}
  fi
fi

_targetEntryFile="$(pwd)/$_entryFile"

if [ ! -d $_pwd ]; then
  mkdir $_pwd
  mkdir $_targetPlatformPath
  mkdir $_targetLocal
  mkdir $_targetRemote
  mkdir $_targetModule
  mkdir $_targetModuleLocal
  mkdir $_targetModuleRemote
else
  if [ ! -d $_targetPlatformPath ]; then
    mkdir $_targetPlatformPath
  fi
  if [ ! -d $_targetLocal ]; then
    mkdir $_targetLocal
  fi
  if [ ! -d $_targetRemote ]; then
    mkdir $_targetRemote
  fi
  if [ ! -d $_targetModule ]; then
    mkdir $_targetModule
  fi
  if [ ! -d $_targetModuleLocal ]; then
    mkdir $_targetModuleLocal
  fi
  if [ ! -d $_targetModuleRemote ]; then
    mkdir $_targetModuleRemote
  fi
fi

if [ "$1" = "local" ]; then # mario-gen-bundle local
  generateBundle ${_targetEntryFile} ${_targetLocal} ${_platform}
elif [ "$1" = "remote" ]; then # mario-gen-bundle remote
  generateBundle ${_targetEntryFile} ${_targetRemote} ${_platform}
elif [ "$1" = "module" ]; then
  if [ "$2" = "local" ]; then # mario-gen-bundle module local module-0
    generateBundle ${_targetEntryFile} ${_targetModuleLocal} ${_platform}
  elif [ "$2" = "remote" ]; then # mario-gen-bundle module remote module-0
    generateBundle ${_targetEntryFile} ${_targetModuleRemote} ${_platform}
  fi
elif [ "$1" = "diff" ]; then # mario-gen-bundle diff
  if [[ $2 ]]; then # mario-gen-bundle diff module-0
    _targetModule="$_pwd/$_platform/$2"
    _targetModuleLocal="$_targetModule/$_local"
    _targetModuleRemote="$_targetModule/$_remote"

    mario-diff-$_platform -p $_pwd -l $_targetModuleLocal -r $_targetModuleRemote -d $_platform -z $_targetModule
  else # mario-gen-bundle diff
    mario-diff-$_platform -p $_pwd -l $_targetLocal -r $_targetRemote -d $_platform
  fi
elif [ "$1" = "clear" ]; then
  # rm -rf $_pwd
  mario-log -t error -i "rm -rf is dangerous"
else
  mario-log -t error -i "
  Your [commandType] is invalid, please type availd [commandType] ( one of 'local', 'remote' or 'diff' ).
    eg:
      mario-gen-bundle [commandType]
  "
fi
