# -*- coding: utf-8 -*-
import actions.util
import sysactions
from actions.goals import update_daily_goals
from actions.login.open_operator_min_level import get_min_level_to_open_operator
from utils import (
    open_user,
    login_user,
    print_open_day_report,
    get_pod_type_and_pos_function,
    change_pod_type_and_pos_function,
    check_current_day,
    get_initial_float,
    save_initial_float,
    user_inserted_initial_amount,
    get_authorization_if_necessary, save_last_authorization, validate_user_level
)


@sysactions.action
def sign_in_table_user(pos_id, user_info):
    validate_user_level(pos_id, user_info)
    return sign_in_user(pos_id, user_info)


def sign_in_user(pos_id, user_info):
    user_id = user_info.get("UserId")
    password = user_info.get("Password")
    long_name = user_info.get("LongName")
    authorization_response = None

    if not check_current_day(pos_id):
        return False

    try:
        sysactions.authenticate_user(user_id, password)
    except sysactions.AuthenticationFailed:
        sysactions.show_messagebox(pos_id, "$INVALID_USERNAME_OR_PASSWORD", "$INFORMATION")
        return False

    user_opened = False
    pos_user = actions.util.get_opened_pos_user(pos_id, user_id)
    if pos_user is None:
        min_level = get_min_level_to_open_operator("TS")
        model = sysactions.get_model(pos_id)
        authorization_response = get_authorization_if_necessary(model, pos_id, user_info, min_level)
        if not authorization_response.success:
            return False

        confirmation_message = "$CONFIRM_OPEN_USER|{}".format(long_name)
        resp = sysactions.show_messagebox(pos_id, confirmation_message, buttons="$OK|$CANCEL", asynch=False)
        if resp is None or resp == 1:
            return False

        user_opened = open_user(pos_id, user_id)

    pod_type, pos_function = get_pod_type_and_pos_function(pos_id)
    if pod_type is None or pos_function is None:
        return False

    initial_float = None
    model = sysactions.get_model(pos_id)

    _, _, session = actions.util.get_operator_info(model, user_id)
    if pos_function != "OT" and not user_inserted_initial_amount(pos_id, session):
        initial_float = get_initial_float(pos_id, pod_type, pos_function)

    if not login_user(pos_id, user_id):
        return False

    if authorization_response:
        save_last_authorization(pos_id, authorization_response.authorized_by, authorization_response.authorized_by_level)

    change_pod_type_and_pos_function(pos_id, pod_type, pos_function)

    if initial_float is not None:
        save_initial_float(initial_float, pos_id, user_id)

    update_daily_goals(
        pos_id=pos_id,
        synchronous=False,
    )

    if user_opened:
        print_open_day_report(pos_id, initial_float)

    return True
