import json
import requests
from threading import Thread
import network_constants as netconst

import logging
LOGGER = logging.getLogger(__name__)

class MessageHandler:
    def __init__(self):
        pass

    def handle_generic(self, body):
        LOGGER.info(f"Received message: {body}")

        message = None
        try:
            message = json.loads(body)
        except ValueError:
            LOGGER.warning("Message is not in JSON format and is ignored")
            return

        if not 'type' in message:
            LOGGER.warning("Message has no type field and is ignored")
            return
        
        if message['type'] == 'new-traces-available':
            self.handle_new_traces_available()
        else:
            LOGGER.info("Message Type could not be processed")
            
    def handle_new_traces_available(self):
        # get all traces and call the Processor
        url = f'http://{netconst.TRACE_RETRIEVAL_HOSTNAME}:{netconst.TRACE_RETRIEVAL_REST_PORT}/api/trace'
        
        # disable university http(s) proxy for name resolution and routing
        session = requests.Session()
        session.trust_env = False
        response = session.get(url)

        if response.status_code == 200:
            traces = response.json()
            # TODO integrate zahras code
            # Thread(target=self._processor.process(traces)).start()            
        else:
            LOGGER.error(f"Could not retrieve JSON from {url} with GET request ({response.status_code})")
