# -*- coding: utf-8 -*-
import sysactions
from sysactions import check_operator_logged, StopAction

from msgbus import TK_POS_USERPAUSE, FM_PARAM, TK_SYS_ACK
from typing import Optional

from .. import logger


@sysactions.action
def pause_user(
    pos_id,                         # type: str
    pos_id_to_show_message=None,    # type: Optional[str]
):
    # type: (...) -> bool

    try:
        check_operator_logged(pos_id)
        pos_id_to_show_message = pos_id if pos_id_to_show_message is None else pos_id_to_show_message
        from table_actions import deselect_table
        deselected_success = deselect_table(
            pos_id=pos_id,
            do_raise=False
        )

        if not deselected_success:
            return False

        msg = sysactions.send_message(
            "POS{}".format(pos_id),
            TK_POS_USERPAUSE,
            FM_PARAM,
            pos_id,
            timeout=60 * 1000000
        )
        if msg.token != TK_SYS_ACK:
            error_code = msg.data.split('\0')[0]
            if error_code == "5003":  # POS BLOCKED BY TIME
                return True

            logger.error("Invalid response from PosCtrl while Pausing user: {} - {}".format(error_code, msg.data))
            _show_error_login_message(pos_id=pos_id_to_show_message)
            return False
    except StopAction:
        return False
    except (Exception, BaseException):
        logger.exception("Exception while pausing user on POS: {}".format(pos_id))
        _show_error_login_message(pos_id=pos_id_to_show_message)
        return False
    return True


def _show_error_login_message(
    pos_id,     # type: str
):
    sysactions.show_messagebox(
        posid=pos_id,
        message="$INVALID_USERNAME_OR_PASSWORD",
    )
