# -*- coding: utf-8 -*-
from sysactions import (
    action,
    get_model,
    check_current_order,
    StopAction,
)

from mw_helper import show_message_dialog
from model.customexception import NotFoundUserError

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 .signout_user import continue_with_opened_tables

from .. import logger


@action
def logoffuser(
    pos_id,         # type: str
    user_id=None,   # type: Optional[str]
):
    # type: (...) -> bool
    logger.debug("Logoff POS %d - Iniciando logoff." % int(pos_id))

    model = get_model(pos_id)
    check_current_order(pos_id, model=model, need_order=False)

    if user_id is None:
        operator = model.find("Operator")
        if operator is None:
            return False

        user_id = operator.get("id")

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

    if pos_user is None:
        show_message_dialog(
            pos_id=pos_id,
            message="$USER_NOT_OPENED",
        )
        return False

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

    try:
        return log_off_user_close_user(pos_id, model, user_id)
    except NotFoundUserError:
        raise StopAction()


@user_authorized_to_execute_action
def log_off_user_close_user(pos_id, model, user_id, auth_data=None):
    return common_close_user(pos_id, model, user_id, authorizer=auth_data)
