import logging
from sysactions import (
    action,
)
from mw_helper import show_message_dialog

from api.table import get_table_service
from actions.util import get_custom_table_seats

logger = logging.getLogger("PosActions")


@action
def do_change_seat_number(
    pos_id,           # type: str
    table_id,         # type: str
    selected_seat,    # type: str
):
    # type: (...) -> bool

    try:
        table_service = get_table_service(pos_id=pos_id)
        table = table_service.get_table(table_id=table_id)
        table_service_dto = table_service.get_service(table_id=table_id)

        if not table.occupied_seats:
            return True

        joined_tables_seats = table_service_dto.custom_properties.get("joinedTablesSeats", "")
        table_seats = table.table_seats if not joined_tables_seats else table.table_seats + int(joined_tables_seats)
        not_occupied_seats = filter(
            lambda item: item not in table.occupied_seats,
            [str(seat) for seat in range(1, table_seats + 1)],
        )
        updated_seat = get_custom_table_seats(
            pos_id=pos_id,
            service_seats="1",
            seats_options=not_occupied_seats,
        )
        if not updated_seat:
            return True

        table_service.change_seat_number(
            table_id=table_id,
            new_seat_number=updated_seat[0],
            old_seat_number=selected_seat,
        )

        return True
    except Exception as ex:
        error_message = "Error changing seat number {} for table {}".format(
            selected_seat,
            table_id,
        )
        logger.info(error_message)
        show_message_dialog(
            pos_id=pos_id,
            title="$ERROR",
            message=ex.message,
        )

    return False
