# -*- coding: utf-8 -*-
import sysactions
from application.repository import AccountRepository
from actions.util import get_operator_info, get_user_level
from ..functions.do_transfer import do_transfer, get_justification
from .. import logger, SIGNED_IN_USER, mb_context
from .utils import close_user

USECS_PER_SEC = 1000000


def common_close_user(pos_id, model, user_id, authorizer=None):
    _, _, session = get_operator_info(model, user_id)
    pod_function = sysactions.get_posfunction(model)
    is_quick_service = model.find("WorkingMode").get("usrCtrlType") != "TS"
    need_ask_justification = False

    if pod_function != "OT":
        response = do_transfer(pos_id, 6, user_id, is_quick_service, authorizer)
        done_transfer = response['done_transfer']
        need_ask_justification = response['need_ask_justification']
        _set_authorizer(pos_id, authorizer, is_quick_service)
        if not done_transfer:
            return False

    logger.debug("Logoff POS %d - Deslogando operador %s" % (int(pos_id), user_id))

    period = sysactions.get_business_period(model)
    if close_user(pos_id, user_id):
        _set_authorizer(
            pos_id=pos_id,
            authorizer=authorizer,
            is_quick_service=is_quick_service
        )
        logger.debug("Logoff POS %d - Operador %s deslogado com sucesso" % (int(pos_id), user_id))
        pos_ot = sysactions.get_posot(model)
        pos_ot.resetCurrentOrder(pos_id)
        sysactions.set_custom(pos_id, "VOIDAUTH_SESSION_DISABLED", "false", persist=True)
        sysactions.clear_custom(pos_id, SIGNED_IN_USER)
    else:
        logger.error("Logoff POS %d - Falha ao deslogar operador %s" % (int(pos_id), user_id))
        sysactions.show_messagebox(pos_id, "$OPERATION_FAILED", "$ERROR")
        return False

    report = "close_operator_report"
    sysactions.print_report(pos_id, model, True, report, pos_id, period, user_id, session, authorizer)

    if pod_function != "OT" and need_ask_justification:
        account_repository = AccountRepository(mb_context)
        get_justification(account_repository, pos_id, session)

    if need_ask_justification:
        sysactions.print_report(pos_id, model, True, report, pos_id, period, user_id, session, authorizer)

    return True


def _set_authorizer(pos_id, authorizer, is_quick_service):
    if authorizer is not None and is_quick_service is False:
        sysactions.set_custom(pos_id, 'Last Manager ID', authorizer)
        sysactions.set_custom(pos_id, 'Authorization Level', get_user_level(authorizer))
