import json
from typing import Any, List

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

from dailygoals_services.interactor.sales_challenge import GetSalesChallengeInteractor

from externals.util import LoggerUtil

logger = LoggerUtil.get_logger_name(__name__)


class GetSalesChallengeProcessor(UuidMessageProcessor):
    def __init__(self, interactor):
        # type: (GetSalesChallengeInteractor) -> None

        super(GetSalesChallengeProcessor, self).__init__()

        self.interactor = interactor

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

        parsed_data = json.loads(data)
        limit = int(parsed_data.get("limit")) if parsed_data.get("limit") else None

        return limit

    def call_business(self, params):
        # type: (Any) -> List

        return self.interactor.get_sales_challenge(params)

    def format_response(self, message_bus, message, event, request, response):
        logger.info("Goals updated for request")
        reply_message = Message(DefaultToken.TK_SYS_ACK, DataType.json, json_serialize(response))
        if message:
            message_bus.reply_message(message, reply_message)
        elif event:
            message_bus.reply_event(event, reply_message)

    def format_exception(self, message_bus, message, event, request, exception):
        exception_name = str(type(exception).__name__)
        logger.info("Error updating total sold from request: {}".format(exception_name))
        self._reply_exception(event, exception, message, message_bus)

    def format_parse_exception(self, message_bus, message, event, data, exception):
        logger.info("Error getting parsing request: {}".format(str(exception)))
        self._reply_exception(event, exception, message, message_bus)

    @staticmethod
    def _reply_exception(event, exception, message, message_bus):
        reply_message = Message(DefaultToken.TK_SYS_NAK, DataType.param, str(exception))
        if message:
            reply_message = Message(DefaultToken.TK_SYS_NAK, DataType.param, str(type(exception).__name__))
            message_bus.reply_message(message, reply_message)
        elif event:
            message_bus.reply_event(event, reply_message)
