# -*- coding: utf-8 -*-
import datetime

import msgbus
import sysactions

from actions.goals import update_daily_goals
from actions.login.open_operator_min_level import get_min_level_to_open_operator
from actions.util import get_operator_info
from utils import (
    open_user,
    login_user,
    print_open_day_report,
    get_pod_type_and_pos_function,
    change_pod_type_and_pos_function,
    close_user,
    get_initial_float,
    save_initial_float,
    user_inserted_initial_amount,
    get_authorization_if_necessary,
    save_last_authorization,
)

from .. import mb_context
from ..drawer.do_open_drawer import doOpenDrawer

USECS_PER_SEC = 1000000


def sign_in_quick_user(pos_id, user_info):
    model = sysactions.get_model(pos_id)
    min_level = get_min_level_to_open_operator("QSR")
    authorization_response = get_authorization_if_necessary(model, pos_id, user_info, min_level)
    if not authorization_response.success:
        return False

    user_id = user_info.get("UserId")
    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 = 0
    _, session = get_operator_info(model, user_id)
    if not user_inserted_initial_amount(pos_id, session):
        initial_float = get_initial_float(pos_id, pod_type, pos_function)

    if open_user(pos_id, user_id) is False:
        return False

    if login_user(pos_id, user_id) is False:
        close_user(pos_id, user_id)
        return False

    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)
    save_initial_float(initial_float, pos_id, user_id)
    update_daily_goals(
        pos_id=pos_id,
        synchronous=False,
    )

    if int(initial_float) > 0:
        doOpenDrawer(pos_id)

    print_open_day_report(pos_id, initial_float)

    return True


def must_change_business_period(model):
    current_date = datetime.datetime.now().strftime("%Y%m%d")
    return model.find("PosState").get("period") != current_date or model.find("PosState").get("state") != "OPENED"


def must_close_business_period(model):
    return model.find("PosState").get("state") == "OPENED" or model.find("PosState").get("state") == "BLOCKED"


def open_business_period(pos_id):
    current_date = datetime.datetime.now().strftime("%Y%m%d")
    business_begin_msg = mb_context.MB_EasySendMessage(
        "POS{}".format(pos_id),
        msgbus.TK_POS_BUSINESSBEGIN,
        msgbus.FM_PARAM,
        "{}\0{}".format(pos_id, current_date),
        timeout=90000000
    )

    if business_begin_msg.token != msgbus.TK_SYS_ACK:
        if business_begin_msg.data:
            raise Exception("Error opening day: {}".format(business_begin_msg.data))

        raise Exception("Error opening day")


def get_pos_service(pos_id):
    return "POS%d" % int(pos_id)
