#!/usr/bin/python3
# @ingroup freda_ttbox
# @copyright
#   SPDX-FileCopyrightText: 2026 European Southern Observatory (ESO)
#   SPDX-License-Identifier: LGPL-3.0-only
#
# @brief fredaGui `main` source file

"""
@file
@author Diego del Valle


The fredaGui provides a user interface to interact with FREDA cameras
"""
import sys


from taurus.qt.qtgui.application import TaurusApplication
import click

from freda.gui.exe.fredaguimainwindow import FredaGuiMainWindow
import ifw.core.stooUtils.consul as consul_utils


@click.command()
@click.option('-n', '--name', default='ccf-req', help='Registered FREDA name in Consul')
@click.option('-u', '--uri', default='none', help='Service URI. E.g. zpb.rr://127.0.0.1:12091')
@click.option('-l', '--log-level', default='ERROR', help='Debugging level',
              type=click.Choice(['ERROR', 'INFO', 'DEBUG'], case_sensitive=False))
@click.option('-r','--style-resource', default='Default', help='Set built-in stylesheet resource',
                type=click.Choice(['Default', 'Combinear', 'Diffnes','Takezo'],
                case_sensitive=True))
@click.option('-d', '--remote-ddt-uri', required=False, multiple=True,
              help='Use remote DDT (uri), can be used multiple times. \nE.g. --remote-ddt-uri zpb.rr://192.168.0.100:12091/broker/Broker1')
@click.option('-p', '--publisher-ddt', required=False, multiple=True,
              help='DDT Publisher name to assign the remote ddt, can be used multiple times\n E.g.  --publisher-ddt pub_1_1_ddt')
@click.pass_context
def main(ctx, name, uri, log_level, remote_ddt_uri, publisher_ddt, style_resource ):
    """
    fredaGui is a solution to connect to FREDA CCF based camera. 
    It allows to be connected via URI (--uri) or by NOMAD service 
    request reply name (--name).

    The usual way of using this GUI would be:

    e.g. 1:

        fredaGui --uri zpb.rr://127.0.0.1:12093

    e.g. 2:

        fredaGui --name freda-ccf-req

    Remote publisher DDT are supported, and can be used by giving the
    DDT ID (--publisher-ddt) together with the remote broker uri 
    (--remote-ddt-uri). Be aware that both parameters can be repeated 
    as much as needed, but the user needs to make sure that both
    parameters appear the same ammount of time. The assigment is based
    on the order of the parameters.

    For example, the next command will assign the broker at URI 
    'zpb.rr://192.168.1.1:12081/broker/broker1' to publisher 'pub_1_1_ddt'
    and broker at URI 'zpb.rr://192.168.1.1:12082/broker/broker2 to 
    publisher pub_1_2_ddt:

        ccfGui --uri zpb.rr://127.0.0.1:12091 -l DEBUG -p pub_1_1_ddt 
    -d zpb.rr://192.168.1.1:12081/broker/broker1 -p pub_1_2_ddt -d
    zpb.rr://192.168.1.1:12082/broker/broker2
    """

    try:
        if uri == "none":
            cons = consul_utils.ConsulClient()
            uri = cons.get_uri(name)
    except Exception as e:
        print(e)
        raise SystemExit


    app = TaurusApplication(
        app_name="fredaGui",
        app_version="1.0.0",
        org_name="ESO",
        org_domain="eso.org"
    )

    # Handling of remote DDT broker  
    if len(remote_ddt_uri) != len(publisher_ddt):
        print("Option --remote-ddt-uri and --publisher-ddt must have the same amount of values")
        exit(1)

    remote_ddt_dic = {}
    for remote_uri, pub_name in zip(remote_ddt_uri, publisher_ddt):
         remote_ddt_dic[pub_name] = remote_uri

    window = FredaGuiMainWindow(ctx, get_uri(ctx), remote_ddt_dic)

    window.menu_set_stylesheet(style_resource)
    window.setWindowTitle("FREDA GUI")
    window.show()
    sys.exit(app.exec_())

def get_uri(cmd_line_ctx):
    name = cmd_line_ctx.params.get("name")
    uri = cmd_line_ctx.params.get("uri")
    if (uri == None):
        cons = consul_utils.ConsulClient()
        uri = cons.get_uri(name)
    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()
