from .system import GuardSystemLoadError

from ._version import __version__

##################################################

def parser_add_system(parser):
    parser.add_argument('system', metavar='<system>', type=str, nargs='?',
                        help="guardian system, by name or module path")
    parser.add_argument('-n', '--name', metavar='<name>', type=str,
                        help="override system name")
    return parser

def parser_add_version(parser):
    parser.add_argument('-v', '--version', action='version',
                        version='Guardian {}'.format(__version__),
                        help="print guardian version and exit")
    return parser

##################################################

def init_system(args, load=False):
    """Initialize (and optionally load) system module

    A SystemExit exception will be thrown if there is a problem
    loading the module.

    """

    if not hasattr(args, 'name'):
        args.name = None
    if not hasattr(args, 'ca_prefix'):
        args.ca_prefix = None

    from . import system

    try:
        sys = system.GuardSystem(args.system,
                                 name=args.name,
                                 ca_prefix=args.ca_prefix)
        if load:
            sys.load()
    except system.GuardSystemError as e:
        raise SystemExit("System error: %s" % e)
    except system.GuardSystemImportError as e:
        raise SystemExit("System import error: %s" % e)
    except GuardSystemLoadError as e:
        raise SystemExit("System load error: %s" % e)

    return sys


def print_states(system, flag_requests=True, requests_only=False, prefix=''):
    """print state enumeration"""
    filters = []
    if requests_only:
        filters.append(('request', True))
    data = list(system.states_iter(filters=filters))
    ilen = max([len(str(s[1])) for s in data])
    for state, index, requestable in data:
        if flag_requests:
            flag = '   '
            if requestable:
                flag = ' * '
        else:
            flag = ' '
        print('{prefix}{index:{ilen}}{flag}{state}'.format(
            index=index,
            state=state,
            flag=flag,
            ilen=ilen,
            prefix=prefix,
        ))


def print_system(system):
    """print system information to stdout"""

    print('ifo: {}'.format(system.ifo))
    print('name: {}'.format(system.name))
    print('module:')
    print('  {}'.format(system.path))

    try:
        system.load()
    except GuardSystemLoadError as e:
        raise SystemExit("System load error: {}".format(e))

    if system.usercode:
        print('usercode:')
        for code in system.usercode:
            print('  {}'.format(code))
    print('CA prefix: {}'.format((system.ca_prefix or '')))
    if system.ca_monitor:
        print('CA monitor: {}'.format(system.ca_monitor))
        print('CA monitor notify: {}'.format(system.ca_monitor_notify))
    print('nominal state: {}'.format((system.nominal or 'NONE')))
    print('initial request: {}'.format((system.request or 'NONE')))
    print('states (*=requestable):')
    print_states(system, prefix='  ')
