#!/usr/bin/python3

"""
@file
@ingroup gui_pylampgui
@copyright ESO - European Southern Observatory

@brief Lamp Engineering Gui
"""
import ifw.core.stooUtils.consul as consul_utils
import pds.ocs.ctrlgui.ctrlgui as ctrlgui

from taurus.qt.qtgui.application import TaurusApplication 
from taurus.core.util.log import Logger 
import click
import sys


@click.command()
@click.option('-n','--name', default="syssup-req", help='registered name in Consul, e.g. syssup-req')
@click.option('-u','--uri', default=None, help='service uri. e.g. zpb.rr://134.171.3.48:22898')
@click.option('-t', '--timeout', default=120000, help='timeout for CII MAL requests in ms')
@click.option('-l', '--loglevel', default='ERROR', help='debugging level',
                type=click.Choice(['ERROR', 'INFO', 'DEBUG'], case_sensitive=False))
@click.pass_context
def main(ctx, name, uri, timeout, loglevel):
    """
    This tool launches the Python FCF GUI.\n
    You must specify one of the '--uri' or '--name' options.

    """
    try:
        app = TaurusApplication(app_name='SUPGUI',
                                app_version='0.0.1',
                                org_name='ESO',
                                org_domain='eso.org',
                                cmd_line_parser=None)

        logger = Logger(app.applicationName())
        if loglevel == 'ERROR':
            logger.setLogLevel(Logger.Error)
        elif loglevel == 'INFO':
            logger.setLogLevel(Logger.Info)
        elif loglevel == 'DEBUG':
            logger.setLogLevel(Logger.Debug)

        new_uri = get_uri(name,uri)
        # pass the click command context to the application
        window = ctrlgui.MainWindow(new_uri, timeout)
        window.show()
        ret = app.exec_()
        sys.exit(ret)
    except Exception as e:
        # Handle exceptions or
        print(e)
        raise SystemExit


def get_uri(service, uri):
    if (uri == None):
        cons = consul_utils.ConsulClient()
        uri = cons.get_uri(service)
    else:
        """ removes any quotes an user may add """
        uri = uri.strip(' " " ')
        uri = uri.strip(' \' \' ')
        """ remove / from the uri because it creates problem with MAL """
        if uri.endswith('/'):
            uri = uri[:-1]
    return uri

if __name__ == '__main__':
    main() 
