import logging
from multiprocessing import Lock

from modelcommon.events import DialogEventType
from sysactions import close_asynch_dialog, show_messagebox

message_lock_dict = Lock()
message_lock = {}
wait_dlg_id = {}


class MessageDialogInteractor(object):
    def __init__(self, params, event_type=None):
        # type: (dict, str) -> None

        self.pos_id = str(params.get("pos_id", None))
        self.params = params
        self.event_type = event_type
        self.logger = logging.getLogger("PosActions")

    def wait_messages(self):
        # type: () -> None

        global wait_dlg_id

        try:
            with self._get_pos_lock(self.pos_id):
                message = self.params.get("message", None)
                if self.event_type == DialogEventType.SHOW_WAIT_SCREEN:
                    message_id = show_messagebox(self.pos_id, message, timeout=120000, asynch=True, buttons="")
                    wait_dlg_id[self.pos_id] = message_id
                if self.event_type == DialogEventType.HIDE_WAIT_SCREEN and wait_dlg_id[self.pos_id] is not None:
                    close_asynch_dialog(self.pos_id,  wait_dlg_id[self.pos_id])
                    del wait_dlg_id[self.pos_id]
        except Exception as _:
            self.logger.exception("Error wait messages")

    @staticmethod
    def _get_pos_lock(pos_id):
        # type: (str) -> None

        with message_lock_dict:
            if pos_id not in message_lock:
                message_lock[pos_id] = Lock()
            return message_lock[pos_id]
