import json
from typing import Optional

from custom_sysactions import user_authorized_to_execute_action
from mw_helper import show_messagebox
from sysactions import action

from do_split_items import (
    filter_sale_line_list,
    validate_fraction_qty,
    split_items,
)


@action
@user_authorized_to_execute_action
def do_split_items_equally(
    pos_id,            # type: str
    sale_line_json,    # type: json
):
    # type: (...) -> Optional[bool]

    from msgbusboundary import MsgBusTableService as tableService

    sale_line_list = filter_sale_line_list(
        pos_id=pos_id,
        sale_line_json=sale_line_json,
    )

    if not sale_line_list:
        return False

    table_id = tableService().get_current_table_id(pos_id=pos_id)
    table_seats = tableService().get_service_seats(
        pos_id=pos_id,
        table_id=table_id,
    )

    if validate_fraction_qty(
        pos_id=pos_id,
        fraction_qty=table_seats,
        message='$CANT_SPLIT_ITEMS_IN_ONE_SEAT_TABLE',
    ) is False:
        return False

    result = show_messagebox(
        posid=pos_id,
        message="$DISCOUNTS_AND_PAYMENTS_WONT_BE_DISTRIBUTED",
        buttons="$OK|$CANCEL",
    )
    if result == 1:
        return False

    split_items(
        pos_id=pos_id,
        table_id=table_id,
        sale_line_list=sale_line_list,
        fraction_qty=table_seats,
        distribute_items_in_seats=True,
    )
