# Testscript for template generation and deploying

from cloud_provider.amazon import Amazon
from template.template import CloudFormationTemplate
from pprint import pprint

if __name__ == "__main__":
    # Amazon Settings
    region = "eu-west-1"
    stack_name = 'TestStack'

    # Template settings
    template_file = '/tmp/template.txt'
    template_json_source_file = 'test-cluster.json'

    # Create template
    cfn_template = CloudFormationTemplate()
    cfn_template.load_json_source(template_json_source_file)
    cfn_template.save_template_file(template_file)
    # pprint(cfn_template.source)

    # Connect to Amazon CloudFormation
    aws = Amazon(region)

    # Deploy CloudFormation Template
    aws.deploy_stack(stack_name, template_file=template_file)

    # Delete Stack if error occured
    # aws.delete_stack(stack_name)
    (options, task) = parse_arguments()

    # Connect to Amazon CloudFormation
    aws = Amazon(options.region)

    if task == "delete" or task == "del":
        # Delete Stack
        aws.delete_stack(options.name)

        # wait and print events
        aws.wait_stack_ready(name=options.name, quiet=False)

    elif task == "deploy" or task == "dep":
        # Deploy CloudFormation template
        if options.template_url:
            aws.deploy_stack(options.name, template_url=options.template_url)

        elif options.template_file:
            # set as default value in OptionParser
            aws.deploy_stack(options.name, template_file=options.template_file)

        else:
            print("ERROR: No template file or template url was given.", file=sys.stderr)
            raise Exception("No template file or template url was given.")

        # wait and print events
        aws.wait_stack_ready(name=options.name, quiet=False)

    elif task == "describe" or task == "des":
        # Describe CloudFormation stack
        result = aws.describe_stack_events(name=options.name)