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

from common_close_user import common_close_user
from custom_sysactions import user_authorized_to_execute_action
from model.customexception import NotFoundUserError
from .signout_user import continue_with_opened_tables

from .. import logger


@action
def logoffuser(pos_id, *args):
    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)

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

    user_id = operator.get("id")
    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)
