#!/usr/bin/env python

from mixcoatl.network.firewall import Firewall
from mixcoatl.network.firewall_rule import FirewallRule
from prettytable import PrettyTable
import argparse
import sys
import os

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--firewall', '-f', type=int, help='Firewall ID')

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

    cmd_args = parser.parse_args()

    if cmd_args.firewall != None:
        results = FirewallRule.all(cmd_args.firewall)
    else:
        parser.print_help()
        sys.exit(1)

    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(["Firewall Rule ID",
                            "Source",
                            "Source Type",
                            "Destination",
                            "Destination Type",
                            "Protocol",
                            "Direction",
                            "Start Port",
                            "End Port",
                            "Permission",
                            "Precedence"])
        for r in results:
            table.add_row([
                r.firewall_rule_id,
                r.source if hasattr(r,'source') else None,
                r.source_type if hasattr(r,'source_type') else None,
                r.destination if hasattr(r,'destination') else None,
                r.destination_type if hasattr(r,'destination_type') else None,
                r.protocol if hasattr(r,'protocol') else None,
                r.direction if hasattr(r,'direction') else None,
                r.start_port if hasattr(r, 'start_port') else None,
                r.end_port if hasattr(r, 'end_port') else None,
                r.permission if hasattr(r,'permission') else None,
                r.precedence if hasattr(r,'precedence') else None])
        table.align = 'l'
        print(table)

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