# -*- coding: utf-8 -*-

from datetime import datetime, timedelta

from dialogmanager import DialogManager


class CapptaCallback(object):
    def __init__(self, dialog_manager):
        # type: (DialogManager) -> None

        self.dialog_manager = dialog_manager
        self.last_response = dict(message=None, timestamp=None)

    def callback(self, pos_id, message, callback_type):
        try:
            if callback_type == "MENSAGEM":
                is_repeated = self._check_if_message_is_not_repeated(message)
                if is_repeated:
                    return

                self.dialog_manager.show_message(pos_id, message)

            elif callback_type == "REQUISITA_ACAO":
                split_message = message.split("\n")
                title = split_message[0]
                user_message = ""
                if len(split_message) > 1:
                    user_message = "\n".join(split_message[1:])

                resp = self.dialog_manager.show_numpad(pos_id, user_message, title)
                return "CANCELA" if not resp else str(resp)

        except BaseException as _:
            return "CANCELA"

    def _check_if_message_is_not_repeated(self, response):
        now = datetime.now()
        if response == self.last_response["message"] and (now - self.last_response["timestamp"]) < timedelta(seconds=3):
            return True
        else:
            self.last_response["message"] = response
            self.last_response["timestamp"] = now
            return False
