# internal shortcut alias
bulk() {
  rlx.commands.bulk "$@";
}

# main
rlx.commands.bulk() {
  local template="bulk";
  if [ -z "${info[database]:-}" ]; then
    console error -- "no database selected";
  elif [ $# -eq 0 ]; then
    console error -- "no bulk command specified";
  else
    local bulk_namespace="bulk.commands";
    local cmd="${1:-}"; shift;
    if ! method.exists? "${bulk_namespace}.${cmd}"; then
      console error -- "unknown bulk command %s" "${cmd}";
    else
      if [ $# -eq 0 ]; then
        console error -- "no bulk document identifiers specified";
      else
        delegate "${bulk_namespace}" "${cmd}" "$@";
      fi
    fi
  fi
}

# add documents
bulk.commands.add() {
  local documents=();
  bulk.arguments.parse add "$@";
  bulk.edit;
}

# delete documents
bulk.commands.rm() {
  local documents=();
  bulk.arguments.parse rm "$@";
  bulk.edit;
}

## PRIVATE

bulk.arguments.parse() {
  local key="$1"; shift;
  local id json rev;
  for id in "$@"
    do
      json="";
      rev="";
      rlx.run couchdb.doc.head \
        "${info[server]:-}" "${info[database]:-}" "${id}";
      if ${flags[success]}; then
        rev="$(etag.parse)";
        rlx.run couchdb.doc.get \
          "${info[server]:-}" "${info[database]:-}" \
          "${id}" "${rev}";
        if ${flags[success]}; then
          json=$( cat "${files[response]}" );
          if [ "${key}" == rm ]; then
            tpl clean;
            tpl set false "doc=${json}";
            tpl parse deleted false;
            json=$( cat "${files[input]}" );
          fi
        else
          console warn -- "could not fetch %s" "${id}?rev=${rev}"
        fi
      elif [ "${http[status]}" == 404 ]; then
        if [ "${key}" == add ]; then
          tpl clean;
          tpl set false "id=${id}";
          tpl parse doc false;
          json=$( cat "${files[input]}" );
        elif [ "${key}" == rm ]; then
          console warn -- "no document %s found for deletion" "${id}";
        fi
      fi
      if [ -n "${json}" ]; then
        documents+=( "${json}" );
      fi
  done
}

bulk.edit() {
  tpl clean;
  tpl set false docs_json=true;
  local IFS=;
  tpl array docs "${documents[@]:-}";
  unset IFS;
  bulk.show;
}

bulk.show() {
  tpl parse "${template}" false \
    || return 1;
  saved() {
    rlx.run couchdb.bulk \
      "${info[server]:-}" "${info[database]:-}" \
      "${files[document]}";
    if ${flags[success]}; then
      rlx.json.print;
    fi
  }
  rlx.edit "${files[input]}";
}
