import logging

from mw_helper import (
    show_message_dialog,
    show_filtered_list_box_dialog
)
from sysactions import (
    show_messagebox,
    StopAction
)
from typing import (
    List,
    Optional
)

from application.interactor import OrderInteractor

logger = logging.getLogger("PosActions")


def display_coupons_from_report(
    pos_id,         # type: str
    initial_date,   # type: str
    end_date,       # type: str
    operator_id     # type: Optional[str]
):
    # type: (...) -> List

    try:
        if initial_date is None or end_date is None:
            raise StopAction()

        benefits = OrderInteractor(pos_id).get_orders_benefit(initial_date, end_date, operator_id)
        if benefits is None or len(benefits) == 1:
            show_messagebox(pos_id, "$ORDER_HAS_NO_APPLIED_DISCOUNT")
            raise StopAction()

        applied_benefits = [benefit["name"] for benefit in benefits]
        sorted_applied_benefits = [applied_benefits[0]] + sorted(list(dict.fromkeys(applied_benefits[1:])))
        options = ["{0}##True".format(benefit) for benefit in sorted_applied_benefits]
        selected_index = show_filtered_list_box_dialog(pos_id, options, "$BENEFIT_REPORT", mask="NOFILTER")

        if selected_index is None:
            raise StopAction()

        chosen_benefit = [x for x in benefits if x["name"] == sorted_applied_benefits[selected_index]]
        return chosen_benefit
    except StopAction:
        raise
    except Exception as ex:
        show_message_dialog(pos_id, "$ERROR", ex.message)
        logger.exception("Error display coupons from report")
        raise StopAction()
