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

from sysactions import get_model, action, get_business_period, get_custom, show_messagebox
from mw_helper import show_message_options_dialog

from actions.util import get_opened_pos_user
from common_close_user import common_close_user
from custom_sysactions import user_authorized_to_execute_action
from typing import Optional
from .. import logger


@action
def sign_out_user(
    pos_id,                     # type: str
    user_id=None,               # type: Optional[str]
    pos_to_close_user=None,     # type: Optional[str]
    current_operator_id=None,   # type: Optional[str]
    auth_data=None,             # type: Optional[str]
):
    # type: (...) -> bool

    if pos_to_close_user is None:
        pos_to_close_user = pos_id

    logger.debug("Logoff POS %d - Iniciando logoff." % int(pos_id))
    model = get_model(posid=pos_to_close_user)

    if user_id is None:
        operator = model.find("Operator")
        if operator is None:
            show_messagebox(pos_id, "$INVALID_USER_OR_PASSWORD", "$INFORMATION")
            return False
        user_id = model.find("Operator").get('id')

    if user_id is None:
        show_messagebox(pos_id, "$INVALID_USER_OR_PASSWORD", "$INFORMATION")
        return False

    pos_user = get_opened_pos_user(
        pos_id=pos_to_close_user,
        user_id=user_id,
    )

    if pos_user is None:
        show_messagebox(pos_id, "$USER_NOT_OPENED", "$INFORMATION")
        return False

    resp = show_message_options_dialog(pos_id, "$OK|$CANCEL", "$INFORMATION", "$CONFIRM_CLOSE_USER|{}"
                                       .format(pos_user.get("name")))
    if resp is None or resp == 1:
        return False

    if not continue_with_opened_tables(
        pos_id=pos_id,
        model=model,
        user_id=user_id,
    ):
        return False

    authorizer = auth_data
    if authorizer is None and current_operator_id and current_operator_id != user_id:
        current_operator = get_opened_pos_user(
            pos_id=pos_to_close_user,
            user_id=current_operator_id,
        )
        authorizer = current_operator.get("name", None) if current_operator is not None else None

    return sign_out_user_close_user(
        pos_id=pos_id,
        model=model,
        user_id=user_id,
        pos_to_close_user=pos_to_close_user,
        authorizer=authorizer,
    )


@user_authorized_to_execute_action
def sign_out_user_close_user(
    pos_id,             # type: str
    model,              # type: str
    user_id,            # type: str
    pos_to_close_user,  # type: str
    auth_data=None,     # type: Optional[str]
    authorizer=None,    # type: Optional[str]
):
    # type: (...) -> bool

    from msgbusboundary import MsgBusTableService as tableService

    authorizer = auth_data if auth_data is not None else authorizer
    return common_close_user(
        pos_id=pos_id,
        model=model,
        user_id=user_id,
        authorizer=authorizer,
        pos_to_close_user=pos_to_close_user,
        table_service=tableService,
    )


def continue_with_opened_tables(pos_id, model, user_id):
    from table_actions import can_close_operator_with_opened_table, has_table_service

    if not has_table_service():
        return True

    is_valid_pod_type = model.find("WorkingMode").get("podType") in ["TS", "FL"]
    is_order_taker = model.find("WorkingMode").get("podFunction") == "OT"
    period = get_business_period(model)

    if is_valid_pod_type and not is_order_taker:
        from tablemgrapi import get_pos_ts
        pos_ts = get_pos_ts(model)
        operator_table = pos_ts.listTables(user_id)
        for table in operator_table:
            table_in_current_business_period = table["businessPeriod"].replace("-", "") == period
            table_is_opened = table['statusDescr'] in ("InProgress", "Seated", "Waiting2BSeated", "Totaled")
            if table_is_opened and table_in_current_business_period:
                if can_close_operator_with_opened_table:
                    ret = show_messagebox(pos_id, "$HAS_OPENED_TABLES_CONTINUE", buttons="$YES|$NO")
                    return ret == 0
                else:
                    show_messagebox(pos_id, "$HAS_OPENED_TABLES")
                    return False

    return True
