#!/usr/bin/env python

import sys
import argparse
import logging
from spotty.commands.clean_logs import CleanLogsCommand
from spotty.commands.create_ami import CreateAmiCommand
from spotty.commands.delete_ami import DeleteAmiCommand
from spotty.commands.run import RunCommand
from spotty.commands.spot_prices import SpotPricesCommand
from spotty.commands.ssh import SshCommand
from spotty.commands.stop import StopCommand
from spotty.commands.start import StartCommand
from spotty.commands.sync import SyncCommand
from spotty.commands.writers.output_writrer import OutputWriter


parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true', help='Show debug messages')

commands = [
    StartCommand,
    StopCommand,
    SshCommand,
    RunCommand,
    SyncCommand,
    CreateAmiCommand,
    DeleteAmiCommand,
    SpotPricesCommand,
    CleanLogsCommand,
]

# add commands
subparsers = parser.add_subparsers()
for command_class in commands:
    subparser = subparsers.add_parser(command_class.get_name(), help=command_class.get_description())
    command_class.configure(subparser)
    subparser.set_defaults(command_class=command_class, parser=subparser)

# parse arguments
args = parser.parse_args()

# logging
logging_level = logging.DEBUG if args.debug else logging.WARNING
logging.basicConfig(level=logging_level, format='%(levelname)s %(message)s')

if not hasattr(args, 'command_class'):
    parser.print_usage()
    sys.exit(1)

output = OutputWriter()

# run a command
try:
    command = args.command_class(args)
    command.run(output)
except ValueError as e:
    output.write('Error:\n'
                 '------\n'
                 '%s' % str(e))
    sys.exit(1)
