#!/usr/bin/env python
#
# Copyright (C) 2013 DNAnexus, Inc.
#
# This file is part of dx-toolkit (DNAnexus platform client libraries).
#
#   Licensed under the Apache License, Version 2.0 (the "License"); you may not
#   use this file except in compliance with the License. You may obtain a copy
#   of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#   WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#   License for the specific language governing permissions and limitations
#   under the License.

import sys, collections
import json
import argparse
from dxpy.utils.printing import *
from dxpy.cli.exec_io import *

parser = argparse.ArgumentParser(description='Creates a new job to run the named function with the specified input.  If successful, prints the ID of the new job.')
parser.add_argument('function', help='Name of the function to run')
parser.add_argument('--name', help='Name for the new job (default is the current job name, plus ":<function>")')
parser.add_argument('--depends-on', metavar='JOB_OR_OBJECT_ID', nargs='*', help='Job and/or data object IDs that must finish or close before the new job should be run.  WARNING: For proper parsing, do not use this flag directly before the *function* parameter.')
parser.add_argument('-i', '--input', help=fill('An input to be added using "<input name>[:<class>]=<input value>", where class can be any job IO class, e.g. "string", "array:string", or "array".  If class is "array" or not specified, the value will be attempted to be parsed as JSON and is otherwise treated as a string', width_adjustment=-24), action='append')
parser.add_argument('-j', '--input-json', help=fill('The full input JSON (keys=input field names, values=input field values)', width_adjustment=-24))
parser.add_argument('-f', '--input-json-file', dest='filename', help=fill('Load input JSON from FILENAME ("-" to use stdin)'))
args = parser.parse_args()

import dxpy.api

job_new_input = {"function": args.function}

if args.name is not None:
    job_new_input["name"] = args.name

if args.depends_on is not None:
    job_new_input["dependsOn"] = args.depends_on

entry_point_inputs = ExecutableInputs()
entry_point_inputs.update_from_args(args)

job_new_input["input"] = entry_point_inputs.inputs

resp = dxpy.api.jobNew(job_new_input)

print resp["id"]
