from scripts.config.json_reader import tags_list, application_config
from scripts.constants.tag_constants import live_tag_data, prev_tag_data
from scripts.core.totaliser_calculator import get_totalized_value
from scripts.core.redis_calculator import get_previous_data
from scripts.core.kairos_calculator import totalizer_calculator
from scripts.util.logger import logger
from scripts.util import mqtt_util
import json
import time

counter = 0


def payload_parser(payload):
    tags = dict()
    for tag in payload['data']:
        if tag in tags_list:
            tags[tag] = {
                'value': payload['data'][tag],
                'timestamp': payload['timestamp']
            }

    if bool(tags):
        logger.info(f'Live Flow Tags : {tags}')
    return tags


def calculate():
    global counter
    if len(live_tag_data) > 0:
        current_tags_data = payload_parser(live_tag_data.pop(0))
        temp_list = {
            'data': {}
        }
        for tag in current_tags_data:
            if current_tags_data.get(tag):

                current_value, current_time = current_tags_data[tag]['value'], current_tags_data[tag]['timestamp']

                logger.info(f"Previous Tag Data : {tag} : {prev_tag_data[tag]}")

                prev_value = prev_tag_data[tag]['previous_value']
                prev_time = prev_tag_data[tag]['previous_time']
                prev_totalized_value = prev_tag_data[tag]['previous_totalized_value']

                if current_time != prev_time:
                    totalized_value = get_totalized_value(current_value, current_time, prev_value, prev_time,
                                                          prev_totalized_value)
                    temp_list['data'][tags_list[tag]] = round(totalized_value, 5)
                    temp_list['site_id'] = tag.split('$')[0]

                    prev_tag_data[tag] = {
                        'previous_value': current_value,
                        'previous_time': current_time,
                        'previous_totalized_value': totalized_value
                    }

        if bool(temp_list['data']):
            counter += 1
            mqtt_util.send_data(message={
                "data": temp_list['data'],
                "site_id": temp_list['site_id'],
                "gw_id": "gw_111",
                "pd_id": "pd_130",
                "msg_id": counter,
                "retain_flag": True,
                "timestamp": current_time,
            })


if __name__ == "__main__":
    logger.info("*************** STARTING ***************")

    mqtt_util.live_data()

    if application_config['kairos_tag'] == 'true':
        if totalizer_calculator():
            while True:
                calculate()

    elif application_config['redis_tag'] == 'true':
        get_previous_data()
        while True:
            calculate()
