#!/usr/bin/env python

from __future__ import print_function

import getopt
import os
import sys
import nsgcli.nsgcli_main
import nsgcli.response_formatter
from nsgcli.version import __version__


usage_msg = """
Interactive NetSpyGlass control script. This script can only communicate with 
NetSpyGlass server running on the same machine.

Usage:

    nsgcli.py --base-url=url [--token=token] [--network=netid] [--region=region] [-U|--utc] [-L|--local] [command]
    
    --base-url:  server access URL without the path, for example 'http://nsg.domain.com:9100'
                 --base-url must be provided.
    --token:     server API access token (if the server is configured with user authentication)
    --region:    if present, all commands will be executed on given region. Equivalent to the command 'region' in
                 the interactive mode.
    --utc:       print values in the column `time` in ISO 8601 format in UTC
    --local:     print values in the column `time` in ISO 8601 format in local timezone (default)
    -v, --version:   print version and exit

    all arguments provided on the command line after the last switch are interpreted together as nsgcli command
"""


class InvalidArgsException(Exception):
    pass


def usage():
    print(usage_msg)


if __name__ == '__main__':

    try:
        opts, args = getopt.getopt(sys.argv[1:],
                                   'hs:b:t:n:r:LUv',
                                   ['help', 'local', 'utc', 'base-url=', 'token=', 'network=', 'region=', 'version'])
    except getopt.GetoptError as ex:
        print('UNKNOWN: Invalid Argument:' + str(ex))
        raise InvalidArgsException

    base_url = os.getenv('NSG_SERVICE_URL')
    token = os.getenv('NSG_API_TOKEN')
    netid = 1
    region = None
    command = ''
    time_format = nsgcli.response_formatter.TIME_FORMAT_ISO_LOCAL

    for opt, arg in opts:
        if opt in ['-h', '--help']:
            usage()
            sys.exit(3)
        elif opt in ('-b', '--base-url'):
            base_url = arg.rstrip('/ ')
        elif opt in ('-a', '--token'):
            token = arg
        elif opt in ('-n', '--network'):
            netid = arg
        elif opt in ['-r', '--region']:
            region = arg
        elif opt in ['-U', '--utc']:
            # prints time in ISO format in UTC
            time_format = nsgcli.response_formatter.TIME_FORMAT_ISO_UTC
        elif opt in ['-L', '--local']:
            # prints time in ISO format in local time zone
            time_format = nsgcli.response_formatter.TIME_FORMAT_ISO_LOCAL
        elif opt in ['-v', '--version']:
            print(__version__)
            sys.exit(0)

    if args:
        command = ' '.join(args)

    if not base_url:
        print('--base-url parameter is mandatory')
        raise InvalidArgsException

    if token is None:
        token = ''

    script = nsgcli.nsgcli_main.NsgCLI(base_url=base_url, token=token, netid=netid, region=region, time_format=time_format)
    script.make_prompt()

    if command:
        script.onecmd(command)
        sys.exit(0)
    else:
        script.summary()
        # script.prompt = ' > '
        # script.ping()
        script.cmdloop()
