#!/usr/bin/env python

from mixcoatl.infrastructure.server_product import ServerProduct
from mixcoatl.geography.region import Region
from mixcoatl import resource_utils, utils
from prettytable import PrettyTable
import os
import time
import argparse
import sys


def lookup_region_id(provider_region_id):
    regions = Region.all()
    for r in regions:
        if r.provider_id == provider_region_id:
            return r.region_id
    return None


if __name__ == '__main__':
    """ List Server Products """
    start = time.time()
    parser = argparse.ArgumentParser()

    group_two = parser.add_mutually_exclusive_group()
    group_two.add_argument('--regionid', '-r', type=int,
                           help='show only results with the DCM REGIONID (use dcm-list-regions to find the IDs)')
    group_two.add_argument('--regionpid', '-p',
                           help='show only results with the provider REGIONPID (for example us-east-1 )')

    group_three = parser.add_mutually_exclusive_group()
    group_three.add_argument('--json', action='store_true',
        help='print API response in JSON format.')
    group_three.add_argument('--xml', action='store_true',
        help='print API response in XML format.')
    group_three.add_argument('--csv', action='store_true',
        help='print API response in XML format.')
    cmd_args = parser.parse_args()

    if cmd_args.regionpid is not None:
        region_id = lookup_region_id(cmd_args.regionpid)
        if region_id is None:
            print "Provider region id: %s not found" % cmd_args.regionpid
            sys.exit(1)
    else:
        region_id = cmd_args.regionid

    results = ServerProduct.all(region_id)

    if cmd_args.xml is True or cmd_args.json is True or cmd_args.csv is True:
        if cmd_args.xml is True:
            payload_format = "xml"
        elif cmd_args.csv is True:
            payload_format = "csv"
        else:
            payload_format = "json"

        print utils.print_format(results, payload_format)
    else:
        table = PrettyTable(["Server Product ID", "Provider Region ID", "Provider Product ID", "Name", "Arch", "Platform", "Currency", "Hourly Rate"])
        for r in results:
            table.add_row([
                r.product_id,
                r.provider_region_id,
                r.provider_product_id,
                r.name,
                r.architecture,
                r.platform,
                r.currency,
                r.hourly_rate])
        table.align = 'l'
        print(table)

    if 'DCM_DEBUG' in os.environ:
        print 'Results returned in', time.time()-start, 'seconds.'
