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

from customer_services.interactor.get_customer.dto import GetCustomerRequest
from customer_services.model import Customer
from customer_services.interactor.get_customer import GetCustomerInteractor

from externals.util import LoggerUtil

logger = LoggerUtil.get_logger_name(__name__)


class GetCustomerProcessor(UuidMessageProcessor):
    def __init__(self, interactor):
        # type: (GetCustomerInteractor) -> None
        
        super(GetCustomerProcessor, self).__init__(event_name=None)
        
        self.interactor = interactor

    def parse_data(self, phone):
        # type: (str) -> GetCustomerRequest
        
        return GetCustomerRequest(phone)
    
    def call_business(self, request):
        # type: (GetCustomerRequest) -> Customer
        
        logger.info("Getting customer from phone {}".format(request.phone))
        customer = self.interactor.get_customer(request)
        
        return customer
    
    def format_response(self, message_bus, message, event, request, response):
        response = json_serialize(response)
        logger.info("Customer returned from phone {}: {}".format(request.phone, response))
        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 getting customer from phone {}: {}".format(request.phone, 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)))
