import paho.mqtt.client as mqtt
import json
import time
from scripts.config.json_reader import application_config, tags_list
from scripts.constants.tag_constants import live_tag_data
from scripts.util.logger import logger

# from scripts.core.totaliser_calculator import calculate_totalized_values

counter = 0


def on_connect(client, userdata, flags, rc):
    logger.info("MQTT : Connected with result code " + str(rc))


def on_message(client, userdata, msg):
    global counter
    try:
        payload = json.loads(msg.payload)
        # logger.info(f"Received Payload : {payload}")
        live_tag_data.append(payload)
    except Exception as es:
        logger.error(f'Exception while fetching data : {es}')


def live_data():
    try:
        client.connect(host=application_config['mqtt']['host'], port=int(
            application_config['mqtt']['port']))

        client.subscribe([(application_config['mqtt']['topic1'], 1), (application_config['mqtt']['topic2'], 1)])
        client.loop_start()
    except Exception as es:
        logger.error(f'exception while connection to mqtt : {es}')


def send_data(message):
    try:
        _topic = f"{application_config['mqtt']['publish_topic']}{message['site_id']}"
        # logger.info(f"Publishing Topic : {_topic}")
        logger.info(f"Publishing Data :{message}")
        msg_info = client.publish(_topic, json.dumps(message), qos=1)
        if msg_info[0] == 4:
            logger.debug("mqtt connection lost")
        else:
            logger.info("MQTT Messaged published successfully")
    except Exception as e:
        logger.exception(f"Exception at MQTT Publish: {e}")
        raise


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
