import os
import sys
import uuid
import time

import redis

from graph_based_intrusion_detection.utils import constants
from graph_based_intrusion_detection.utils import config
from graph_based_intrusion_detection.utils.logging import create_logger
from graph_based_intrusion_detection.utils.network_transport_utils import deserialize, serialize


def start_network_visualizer(worker_id: str):
    """
    Process that visualizes info about the network state
    :param worker_id: network id
    :return: None
    """

    logger = create_logger(f"Network-Visualizer {worker_id}")
    logger.info(f"Worker started")

    redis_host = redis.Redis(host='localhost', port=6379, db=0)
    while True:
        node_registry_raw = redis_host.get(constants.NODE_REGISTRY_KEY)
        if node_registry_raw is None:
            print("Node registry not found in redis, retrying on next iteration")
            time.sleep(1)
            continue

        # clear output
        os.system('clear')

        node_registry = deserialize(node_registry_raw)

        for node, node_data in node_registry.items():
            print(f"Node {node}, last updated: {node_data['last_updated']}")
            if "results" in node_data:
                for key, value in node_data["results"].items():
                    print(f"\t{key}: {value}", end=",")
            else:
                print(f"\tNo results for node {node}")
            print()

        time.sleep(1)


if __name__ == "__main__":
    if len(sys.argv) < 2:
        worker_id = str(uuid.uuid4())
    else:
        worker_id = sys.argv[1]

    start_network_visualizer(worker_id)
