# -*- coding: utf-8 -*-
from sysactions import action, get_business_period, get_model, check_current_order, get_custom

from common_close_user import common_close_user
from custom_sysactions import user_authorized_to_execute_action

from .. import logger
from ..pos.check_table_status import has_tab_or_tables_opened, show_open_table_dialog


@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)
    period = get_business_period(model)

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

    user_id = operator.get("id")
    if has_tab_or_tables_opened(period, pos_id, user_id):
        show_open_table_dialog(pos_id)
        return False

    return log_off_user_close_user(pos_id, model, user_id)


@user_authorized_to_execute_action
def log_off_user_close_user(pos_id, model, user_id, auth_data=None):
    if auth_data is None:
        authorizer = get_custom(model, 'Last Manager ID')
        auth_data = authorizer

    return common_close_user(pos_id, model, user_id, authorizer=auth_data)
