#!/usr/bin/env python

# This script will return the job of the request to create the/a launch configuration.

from mixcoatl.automation.launch_configuration import LaunchConfiguration
from prettytable import PrettyTable
import argparse
import pprint
import sys,os
import json

def print_verbose(name,gid):
    print name, gid

def validate_input(update_file):
    """
    This method validates the input file. Returns true if the JSON is valid, false
    otherwise.
    """
    try:
        json.load(open(update_file))
        #print "Valid JSON"
        return True
    except ValueError:
        print "Invalid JSON. Exiting."
        exit(-1)
        return False

def is_valid_file(parser, arg):
    """Check to see if the file passed to -i is in fact a file. If it is, check to see if
       it's a valid json format."""
    if not os.path.isfile(arg):
       parser.error("The file %s does not seem to be a file at all! Exiting for safety reasons." %arg)
       sys.exit(1)
    else:
       if validate_input(arg):
           return True
       else:
           print "Invalid JSON. Exiting"
           sys.exit(1)

def create_launch_configuration_from_file():
    """Create launch configuration as defined in the JSON elements in specified file"""
    parser = ArgumentParser(description="Tier JSON Descriptor")
    if is_valid_file(parser,filename):
        f=open(filename,'r')
        json_object = json.load(f)

    lc = LaunchConfiguration()
    for value in json_object.values():
        for v in range(0,len(value)):
            new_tier.deployment=value[v]['deployment']['deploymentId']
            new_tier.description = value[v]['description']
            new_tier.name = value[v]['name']
            new_tier.budget = value[v]['budget']
            new_tier.minimum_servers = value[v]['minimumServers']
            new_tier.maximum_servers = value[v]['maximumServers']
            new_tier.breach_increment = value[v]['breachIncrement']
            new_tier.breach_period = value[v]['breachPeriodInMinutes']
            new_tier.cooldown_period = value[v]['cooldownPeriodInMinutes']
            new_tier.lower_cpu_threshold = value[v]['lowerCpuThreshold']
            new_tier.upper_cpu_threshold = value[v]['upperCpuThreshold']
            new_tier.lower_ram_threshold = value[v]['lowerRamThreshold']
            new_tier.upper_ram_threshold = value[v]['upperRamThreshold']
            #result=new_tier.create()
            #print new_tier.current_job

if __name__ == '__main__':
    """Creates a new launch configuration, returns the ID of the create launch configuration *job*."""
    parser = argparse.ArgumentParser()
    parser.add_argument('--region', '-r', type=int, help='The region in which the LC will be created.')
    parser.add_argument('--primary-product-id', help='The primary product size.')
    parser.add_argument('--secondary-product-id', help='((Optional) The secondary product size.')
    parser.add_argument('--tier', '-t', help='The tier.')
    parser.add_argument('--firewalls', '-f', help='The security group.')
    parser.add_argument('--primary-machine-image', '-m', type=int, help='The primary machine image to use.')
    parser.add_argument('--secondary-machine-image', '-s', type=int, help='((Optional) The secondary machine image to use.')
    parser.add_argument('--server-name-template', help='((Optional) The secondary machine image to use.')
    parser.add_argument('-i', dest="filename", required=False,
        help="Input file for creating a launch configuration", metavar="FILE")
    parser.add_argument('--verbose', '-v', action='store_true', default=False, help='Print out verbose information about the launch configuration creation.')

    cmd_args = parser.parse_args()
    region=cmd_args.region
    primary_product_id=cmd_args.primary_product_id
    secondary_product_id=cmd_args.secondary_product_id
    tier=cmd_args.tier
    firewalls=cmd_args.firewalls
    primary_machine_image=cmd_args.primary_machine_image
    secondary_machine_image=cmd_args.secondary_machine_image
    server_name_template=cmd_args.server_name_template
    filename=cmd_args.filename

    if cmd_args.filename:
        print "\nCreating launch configuration from file.\nIgnoring all other command line arguments.\n"
        create_tier_from_file()
        sys.exit(0)

    if region is None or primary_product_id is None or tier is None or firewalls is None or primary_machine_image is None:
        parser.print_help()
        sys.exit(1)

    lc = LaunchConfiguration()

    lc.region = region
    lc.primary_product_id = primary_product_id
    lc.secondary_product_id = secondary_product_id
    lc.primary_machine_image = primary_machine_image
    lc.secondary_machine_image = secondary_machine_image
    lc.server_name_template = server_name_template
    lc.tier = tier
    lc.firewalls = firewalls
    lc.region = region

    result = lc.create()

    # return Job ID
    print lc.current_job
