# -*- coding: utf-8 -*-
from threading import Thread

import bustoken
from typing import Optional

from actions import mb_context
from sysactions import (
    get_model,
    action,
    show_any_dialog,
)
from systools import sys_log_exception


@action
def show_daily_goals(pos_id, operator_id, show_amount_chart, show_item_chart, show_operator_table, show_average_chart):
    update_daily_goals(pos_id)

    return show_any_dialog(pos_id, "dailyGoals", "message", "title", "", "", "", 600000,
                           operator_id + "|" + show_amount_chart + "|" + show_item_chart + "|" +
                           show_operator_table + "|" + show_average_chart,
                           "", "", "", None, False)


def update_daily_goals(
    pos_id,             # type: str
    synchronous=True,   # type: Optional[bool]
):
    # type: (...) -> None

    if synchronous:
        _send__message_to_update_goals(pos_id)
        return

    Thread(target=_send__message_to_update_goals, args=(pos_id,)).start()


def _send__message_to_update_goals(pos_id):
    try:
        model = get_model(pos_id)
        daily_goals = model.findall("Custom[@name='DAILY_GOALS']")
        if len(daily_goals) == 0:
            mb_context.MB_EasySendMessage("DailyGoals", bustoken.TK_DAILY_GOALS_UPDATE_TOTAL_SOLD)
    except BaseException as _:
        sys_log_exception("[update_daily_goals]")
