import logging

from mw_helper import show_keyboard
from sysactions import (
    action,
    show_messagebox,
)
from xml.etree import cElementTree as eTree

from api.table import get_table_service
from custom_sysactions import (
    user_must_be_logged,
)
from table_manager_api.dto.exception import TableError
from typing import Optional

logger = logging.getLogger("TableActions")


@action
@user_must_be_logged
def join_tabs(
    pos_id,     # type: str
    tab_id,     # type: Optional[str]
):
    # type: (...) -> None

    while True:
        tab_name = show_keyboard(
            posid=pos_id,
            message="$TYPE_TAB_NAME",
        )

        if not tab_name:
            return

        tab_id = _join_tabs(
            pos_id=pos_id,
            current_tab_id=tab_id,
            tab_name_to_join=tab_name,
        )


def _join_tabs(
    pos_id,             # type: str
    current_tab_id,     # type: str
    tab_name_to_join,   # type: str
):
    # type: (...) -> str

    from table_actions import create_table_modified_event

    try:
        table_picture_dto = get_table_service(pos_id=pos_id).join_tabs(
            current_tab_id=current_tab_id,
            tab_name_to_join=tab_name_to_join,
        )

        create_table_modified_event(
            pos_id=pos_id,
            table_picture=eTree.tostring(table_picture_dto.to_xml()),
        )

        return table_picture_dto.table.table_id

    except TableError as ex:
        show_messagebox(
            posid=pos_id,
            message=str(ex),
        )
        logger.info("Error trying to join tab {} to tab ID {}: ".format(tab_name_to_join, current_tab_id))

        return current_tab_id

    except (Exception,):
        show_messagebox(
            posid=pos_id,
            message="$JOIN_TABLES_ERROR",
        )
        logger.exception("Error join tab {} to tab ID {}".format(tab_name_to_join, current_tab_id))

        return current_tab_id
