import json

from helper import json_serialize
from messagebus import Message, DefaultToken, DataType
from messageprocessorutil import UuidMessageProcessor
from typing import Dict, Any

from customer_services.interactor.add_customer import AddCustomerInteractor
from customer_services.interactor.add_customer.dto import AddCustomerRequest

from externals.util import LoggerUtil

logger = LoggerUtil.get_logger_name(__name__)


class AddCustomerProcessor(UuidMessageProcessor):
    def __init__(self, interactor):
        # type: (AddCustomerInteractor) -> None
    
        super(AddCustomerProcessor, self).__init__()
        
        self.interactor = interactor

    def parse_data(self, data):
        # type: (Any) -> AddCustomerRequest

        request = json.loads(data.decode("utf-8"))  # type: Dict[str, str]
        return AddCustomerRequest(request["phone"],
                                  request["document"],
                                  request["name"],
                                  request["zip_code"],
                                  request["city"],
                                  request["street"],
                                  request["neighborhood"],
                                  request["number"],
                                  request["complement"],
                                  request["reference_point"])

    def call_business(self, request):
        # type: (AddCustomerRequest) -> None

        logger.info("Adding customer for request: {}".format(json_serialize(request)))
        self.interactor.add_customer(request)

    def format_response(self, message_bus, message, event, request, response):
        logger.info("Customer added for request: {}".format(json_serialize(request)))
        message_bus.reply_message(message, Message(DefaultToken.TK_SYS_ACK, DataType.param, response))

    def format_exception(self, message_bus, message, event, request, exception):
        exception_name = str(type(exception).__name__)
        logger.info("Error adding customer from request {}: {}".format(json_serialize(request), exception_name))
        reply_message = Message(DefaultToken.TK_SYS_NAK, DataType.param, exception_name)
        message_bus.reply_message(message, reply_message)

    def format_parse_exception(self, message_bus, message, event, data, exception):
        logger.info("Error getting parsing request: {}".format(str(exception)))
        message_bus.reply_message(message, Message(DefaultToken.TK_SYS_NAK, DataType.param, str(exception)))
