from datetime import date

from actions.update import get_catalog_version_to_apply, get_message_update, apply_update
from actions.rupture.get_ruptured_products import has_rupture_items
from actions.rupture.clean_rupture import clean_rupture_on_open_day
from msgbus import TK_SYS_ACK
from sysactions import (
    show_messagebox,
    format_date,
    StopAction,
    get_model,
    get_poslist,
    get_business_period,
)

BUTTONS = "$OK|$CANCEL"


class OpenDayInteractor(object):
    def process_before_open_day(
        self,
        pos_id,  # type: int
    ):
        # type: (...) -> None

        self._check_has_update_menu(pos_id)

        if self._is_first_pos_opening_current_day():
            clean_rupture_on_open_day()

    @staticmethod
    def _check_has_update_menu(
        pos_id,  # type: int
    ):
        # type: (...) -> None

        today = date.today().strftime("%Y%m%d")
        confirm_message = "$CONFIRM_OPEN_CURRENT_DAY|{0}".format(format_date(today))
        msg = get_catalog_version_to_apply()
        if msg.token == TK_SYS_ACK:
            get_message_update(pos_id, "$APPLYING_UPDATE_MENU_VERSION_PENDING|" + msg.data)
            has_rupture_items(pos_id)
            applied_update = apply_update(pos_id)
            if not applied_update:
                confirm_message = "$UPDATE_MENU_ERROR_PROCEED"

        confirm = show_messagebox(pos_id, message=confirm_message, buttons=BUTTONS)
        if (confirm is None) or (confirm == 1):
            raise StopAction()

    @staticmethod
    def _is_first_pos_opening_current_day():
        # type: (...) -> bool

        pos_list = sorted(get_poslist())
        current_business_period = date.today().strftime("%Y%m%d")

        for pos in pos_list:
            model = get_model(posid=pos)
            business_period = get_business_period(model=model)
            if current_business_period == business_period:
                return False

        return True
