"""
Name: keolis_avms
Title: 
Author: Cooper
Date: 25/03/2021

Desc:

"""
import time
import _thread

import xmltodict

from hanip.itxpt import itxpt_avms
from hanip.itxpt import itxpt_mqtt


keolis_avms_app_ver = ""

class KeolisAVMS(object):
    def __init__(self, config_dict, hw_dict, conf_dir, data_dir):
        self.config_dict = config_dict
        self.hw_dict = hw_dict
        self.conf_dir = conf_dir
        self.data_dir = data_dir

    def run(self):
        if self.hw_dict["hw_type"] == "con":
            print("MQTT service running on Console")
            avms_service = ConsoleKeolis(self.config_dict, self.hw_dict, self.conf_dir, self.data_dir)
        else:
            print("MQTT service running on Sign")
            avms_service = SignKeolis(self.config_dict, self.hw_dict, self.conf_dir, self.data_dir)

        avms_service.run()

class ConsoleKeolis(object):
    def __init__(self, config_dict, hw_dict, conf_dir, data_dir):
        self.config_dict = config_dict
        self.hw_dict = hw_dict
        self.conf_dir = conf_dir
        self.data_dir = data_dir

        self.itxpt_mqtt = itxpt_mqtt.ConsoleMQTT(self.config_dict,
                                                 self.hw_dict,
                                                 self.conf_dir,
                                                 self.data_dir
                                                 )



    def setup_console_task(self):
        from hanip.onionip.console import console_task
        self.ct = console_task.ConsoleTask(self.config_dict, self.hw_dict, self.conf_dir, self.data_dir)
        # _thread.start_new_thread(self.ct.run, ())
        _thread.start_new_thread(self.ct.run_sign_data_mode, ())

    def setup_avms_client(self):
        """
        Sets up the client
        :return:
        """
        #TODO need to modify this to support the new client
        self.config_dict["AVMS_basic_mode"] = True

        self.itxpt_avms = itxpt_avms.ITxPTAVMS(self.config_dict,
                                                 self.hw_dict,
                                                 self.conf_dir,
                                                 self.data_dir
                                                 )

        _thread.start_new_thread(self.itxpt_avms.run, ())

    def displayVersion(self):
        if keolis_avms_app_ver == "":
            module_ver = self.hw_dict["onion_ver"]
        else:
            module_ver = "%s_%s" % (self.hw_dict["onion_ver"], keolis_avms_app_ver)

        self.ct.update_console_display("Keolis App Ver: %s" % (module_ver), 0, 5)

    def check_avms(self):
        """
        Originally this module parsed the AVMS data to extract the relevant data, now no longer needs to and only
        needs to check if there is any data there and send it to the console.
        Old code left there for keepsakes just incase...
        :return:
        """
        destcode = self.itxpt_avms.data_consumer.destination_code
        if destcode != None:
            self.ct.update_remote_code(destcode)
        else:
            print("Not in service!")
            self.ct.update_remote_code("0000")


    def generate_console_status(self):
        publish_topic = self.config_dict["MQTT_status_topic"].replace("#", "Console")

        if self.ct.wdm_enable:
            wdm_status = self.ct.wdm.generate_wdm_status()
        else:
            wdm_status = "Not Enabled"

        #Todo add AVMS service status to this as well
        avms_status = {
            "service_found": self.itxpt_avms.avms_server_found,
            "service_subscribed": self.itxpt_avms.avms_operation_details["plannedpattern"]["subscribed"],
            "service_ip": self.itxpt_avms.service_ip,
            "service_port": self.itxpt_avms.service_port,
            "service_errors": self.itxpt_avms.http_error,
            "note": "Check the config for static AVMS parameters"
        }

        console_data = {
            "manual_code": self.ct.manual_code,
            "remote_code": self.ct.remote_code,
            "remote_set_code": self.ct.remote_set_code,
            "test_mode": self.ct.test_mode,
            "avms_status": avms_status,
            "wdm_status": wdm_status,
            "sign_map_table": self.ct.sign_mapping_table
        }

        current_status = self.itxpt_mqtt.status_handler.get_console_status(time.time(), console_data)
        self.itxpt_mqtt.mqttc.publish_data(publish_topic, current_status)

    def run_legacy(self):
        self.itxpt_mqtt.setup_mis()
        self.itxpt_mqtt.setup_mqtt_register()
        self.itxpt_mqtt.setup_mqtt_client()
        self.setup_console_task()        ##This needs modifying to accept the setting of dest codes
        self.itxpt_mqtt.setup_template_gen()
        self.itxpt_mqtt.setup_config_updater()

        self.displayVersion()
        self.setup_avms_client()

        try:
            while 1:
                if self.ct.update_flags["eric"] or self.ct.update_flags["json"] or self.ct.update_flags["config"]:
                    self.ct.stop = True
                    return

                self.check_avms()

                #TODO Check that mapping is supported due to the console replying with HCP and not just the sign data
                self.itxpt_mqtt.get_destination_data(ext_code=self.ct.manual_code, test_mode=self.ct.test_mode)
                time.sleep(2)

        except KeyboardInterrupt:
            self.ct.stop = True

    def run(self):
        self.itxpt_mqtt.setup_mis()
        self.itxpt_mqtt.setup_mqtt_register()
        self.itxpt_mqtt.setup_mqtt_client()
        self.setup_console_task()        ##This needs modifying to accept the setting of dest codes
        self.itxpt_mqtt.setup_config_updater()
        self.itxpt_mqtt.setup_status_handler()

        self.displayVersion()
        self.setup_avms_client()

        status_timer = 0
        try:
            while 1:
                if self.ct.update_flags["config"]:
                    self.ct.stop = True
                    return
                if self.ct.stop:
                    return

                if (time.time() - status_timer) > 10:
                    self.generate_console_status()
                    status_timer = time.time()

                self.check_avms()
                print("")
                self.itxpt_mqtt.get_display_data(self.ct.manual_code, self.ct.route_code, self.ct.test_mode, self.ct.sign_messages)
                time.sleep(2)

        except KeyboardInterrupt:
            self.ct.stop = True


class SignKeolis(object):
    """
    This portion isn't necessary because as far as the signs are concerned they're still MQTT signs,
    so perhaps this part should import itxpt_mqtt instead?
    """
    def __init__(self, config_dict, hw_dict, conf_dir, data_dir):
        self.config_dict = config_dict
        self.hw_dict = hw_dict
        self.conf_dir = conf_dir
        self.data_dir = data_dir

    def run(self):
        pass

if __name__ == "__main__":
    pass
