#compdef force
# ------------------------------------------------------------------------------
# Copyright (c) 2017 Github zsh-users - http://github.com/zsh-users
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of the zsh-users nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ------------------------------------------------------------------------------
# Description
# -----------
#
#  Completion script for force CLI 0.22.39 (https://github.com/heroku/force).
#
# ------------------------------------------------------------------------------
# Authors
# -------
#
#  * Peter Limbach <https://github.com/pelim>
#
# ------------------------------------------------------------------------------

local -a _1st_arguments
_1st_arguments=(
    'apiversion:Display/Set current API version'
    'login:force login [-i=<instance>] [<-u=username> <-p=password>]'
    'logout:Log out from force.com'
    'logins:List force.com logins used'
    'active:Show or set the active force.com account'
    'whoami:Show information about the active account'
    'describe:Describe the object or list of available objects'
    'sobject:Manage standard & custom objects'
    'bigobject:Manage big objects'
    'field:Manage sobject fields'
    'record:Create, modify, or view records'
    'bulk:Load csv file use Bulk API'
    'fetch:Export specified artifact(s) to a local directory'
    'import:Import metadata from a local directory'
    'export:Export metadata to a local directory'
    'query:Execute a SOQL statement'
    'apex:Execute anonymous Apex code'
    'trace:Manage trace flags'
    'log:Fetch debug logs'
    'eventlogfile:List and fetch event log file'
    'oauth:Manage ConnectedApp credentials'
    'test:Run apex tests'
    'security:Displays the OLS and FLS for a give SObject'
    'version:Display current version'
    'update:Update to the latest version'
    'push:Deploy artifact from a local directory'
    'aura:force aura push -f <filepath>'
    'password:See password status or reset password'
    'notify:Should notifications be used'
    'limits:Display current limits'
    'help:Show this help'
    'datapipe:Manage DataPipes'
)

local -a _field_arguments


_apex_types=(
  'string' 'textarea' 'longtextarea' 'richtextarea'
  'boolean' 'double' 'number' 'autonumber' 'picklist' 
  'lookup' 'masterdetail' 'geolocation'
)

_field_arguments=(
   'list' 'create' 'delete' 'type'
)

_sobject_arguments=(
   'list' 'create' 'delete'
)

_bulk_arguments=(
  'insert:upload a .csv file to insert records'
  'update:upload a .csv file to update records'
  'query:run a SOQL statement to generate a .csv file on the server'
  'retrieve:retrieve a query generated .csv file from the server'
  'job:get information about a job based on job Id'
  'batch:get detailed information about a batch within a job based on job Id and batch Id'
  'batches:get a list of batches associated with a job based on job Id'
)

__sobject_list() {
  _wanted application expl 'sobjects' compadd $(force sobject list)
}

__log_list() {
  _wanted application expl 'logfiles' compadd $(force log | grep  -o -e '07\w*')
}

__login_user_list() {
   # remove active user string, remove colors & print the username
  _wanted application expl 'usernames' compadd $(force logins | sed 's/(active)//' | sed 's,$(printf "\033"")\\[[0-9;]*[a-zA-Z],,g' | awk '{print $1}')
}

__login_instance_list() {
  _wanted application expl 'instances' compadd $(force logins | awk '{print $3}' | sed 's/https:\/\///') 
}

__sobject_command () {
    local curcontext="$curcontext" state line
    typeset -A opt_args

    _arguments -C \
        ':command:->command' \
        '*::options:->options'

   case $state in
       (command)
           _describe -t commands "sobject commands" _sobject_arguments
           return
       ;;

       (options)
           case $line[1] in
               (delete)
                   _arguments ':feature:__sobject_list'
               ;;
           esac
       ;;
    esac
}

__field_command () {
    local curcontext="$curcontext" state line
    typeset -A opt_args

    _arguments -C \
        ':command:->command' \
        '*::options:->options'

   case $state in
       (command)
           _describe -t commands "field commands" _field_arguments
           return
       ;;

       (options)
           case $line[1] in
              (list)
                   _arguments ':feature:__sobject_list'
              ;;
              (type)
                   _describe -t commands "apex types" _apex_types
                   return
              ;;
           esac
       ;;
    esac
}

local expl
local -a active logins

local curcontext="$curcontext" state line
local -A opt_args

_arguments -C \
  ':command:->command' \
  '*::options:->options'

case $state in
  (command)
      _describe -t commands "force commands" _1st_arguments
      return
  ;;

  (options)
    case $line[1] in
      (help)
          _describe -t commands "command help" _1st_arguments
          return
      ;;

      (login)
        _arguments \
          '-u[salesforce user]:userame:__login_user_list' \
          '-i[salesforce instance]:instance:__login_instance_list' \
          '-p[salesforce password]'
      ;;
      (bulk)
        _arguments \
          '-c[bulk command]:_bulk_arguments'
      ;;

      (log)
        _arguments ':feature:__log_list'
      ;;

      (field)
          __field_command
      ;;

      (sobject)
          __sobject_command
      ;;

    esac
  ;;
esac