import json

from helper import json_serialize
from typing import Any

from messagebus import Message, DefaultToken, DataType
from messageprocessorutil import UuidMessageProcessor

from customer_services.interactor.update_customer import UpdateCustomerInteractor
from customer_services.interactor.update_customer.dto import UpdateCustomerRequest

from externals.util import LoggerUtil

logger = LoggerUtil.get_logger_name(__name__)


class UpdateCustomerProcessor(UuidMessageProcessor):
    def __init__(self, interactor):
        # type: (UpdateCustomerInteractor) -> None
        
        super(UpdateCustomerProcessor, self).__init__()
        
        self.interactor = interactor
    
    def parse_data(self, data):
        # type: (Any) -> UpdateCustomerRequest
        
        request = json.loads(data)
        return UpdateCustomerRequest(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: (UpdateCustomerRequest) -> None

        logger.info("Updating customer for request: {}".format(json_serialize(request)))
        self.interactor.update_customer(request)
    
    def format_response(self, message_bus, message, event, request, response):
        logger.info("Customer updated 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 updating 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)))
