# -*- coding: utf-8 -*-
import sysactions
from actions.login.common_close_user import set_authorizer
from typing import Optional

from actions.login.signout_user import sign_out_user
from actions.util.list_users import get_opened_users
from custom_sysactions import user_authorized_to_execute_action


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

    model = sysactions.get_model(pos_id)
    manager_id = sysactions.get_custom(
        model=model,
        key='Last Manager ID',
    )

    logged_out_user = execute_sign_out_user(
        pos_id=pos_id,
        current_operator_id=current_operator_id,
        auth_data=manager_id,
    )

    set_authorizer(
        pos_id=pos_id,
        authorizer=manager_id,
        is_quick_service=False,
    )

    return logged_out_user


@sysactions.action
@user_authorized_to_execute_action
def close_operators(
    pos_id,                  # type: str
    current_operator_id,     # type: str
    auth_data=None,          # type: Optional[str]
):
    # type: (...) -> bool

    return execute_sign_out_user(
        pos_id=pos_id,
        current_operator_id=current_operator_id,
        auth_data=auth_data,
    )


def execute_sign_out_user(
    pos_id,                 # type: str
    current_operator_id,    # type: str
    auth_data=None,         # type: Optional[str]
):
    # type: (...) -> bool

    model = sysactions.get_model(posid=pos_id)
    sysactions.check_current_order(
        posid=pos_id,
        model=model,
        need_order=False,
    )

    pos_to_close_user, user, _ = get_opened_users(pos_id=pos_id)

    if user is None:
        return False

    return sign_out_user(
        pos_id=pos_id,
        user_id=user.get("id"),
        pos_to_close_user=pos_to_close_user,
        current_operator_id=current_operator_id,
        auth_data=auth_data,
    )
