import json

import logging
LOGGER = logging.getLogger(__name__)

class MessageHandler:
    MSG_NOT_JSON = "Message is not in JSON format and is ignored"
    MSG_NO_TYPE = "Message has no type field and is ignored"
    MSG_NOT_PROCESSED = "Message Type could not be processed"
    MSG_TRACE_PROCESSED = "Message handled as blockchain-transaction"

    _mongo_repo = None
    _message_sender = None

    def __init__(self, mongo_repo, message_sender):
        self._mongo_repo = mongo_repo
        self._message_sender = message_sender
        self._message_sender.create_message_destination('datahub', 'direct')

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

        message = None
        try:
            message = json.loads(body)
        except (ValueError, TypeError):
            result = self.MSG_NOT_JSON
            LOGGER.warning(result)
            return result

        if not 'type' in message:
            result = self.MSG_NO_TYPE
            LOGGER.warning(result)
            return result
        
        if message['type'] == 'blockchain-transaction':
            self.handle_blockchain_transaction(message['content'])
            result = self.MSG_TRACE_PROCESSED
        else:
            result = self.MSG_NOT_PROCESSED

        LOGGER.info(result)
        return result
            
    def handle_blockchain_transaction(self, transaction):
        # TODO think if inserting makes sense (or just caching while processing if ms goes down)
        # self._mongo_repo.insert_trace(transaction)

        # TODO convert raw input to prepared data based on key 'ApplicationType'
        
        # inform semantic linking microservice
        msg = {'type': 'new-traces-available'}
        self._message_sender.send_message('datahub', 'semantic-linking', json.dumps(msg))