import logging

from xml.etree import cElementTree as eTree

from helper import remove_accents
from typing import Dict, List

from sysactions import (
    get_model,
    show_order_preview,
    get_business_period,
    StopAction,
    show_messagebox
)


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

        self.logger = logging.getLogger("PosActions")
        self.pos_id = pos_id

    def get_opened_tabs(
            self
    ):
        # type: (...) -> List

        from tablemgrapi import get_pos_ts

        try:
            model = get_model(self.pos_id)
            pos_ts = get_pos_ts(model)
            period = get_business_period(model)
            tables = pos_ts.listTables(with_props=1)
            opened_tabs = []
            for table in tables:
                table_is_opened = table['statusDescr'] in ("InProgress", "Seated", "Waiting2BSeated", "Totaled")
                table_is_opened = table_is_opened and table["businessPeriod"].replace("-", "") == period
                if table_is_opened and self._is_tab(table):

                    table_info = pos_ts.getTableInfo(table["id"])
                    table_picture_xml = eTree.XML(table_info)
                    properties = table_picture_xml.find(".//Properties")

                    table_name = remove_accents(table_picture_xml.get("name"))
                    customer = remove_accents(properties.get("CUSTOMER_NAME") or table_name)
                    customer_phone = remove_accents(properties.get("CUSTOMER_PHONE") or "")

                    opened_tabs.append({
                        "tableId": table["id"],
                        "name": table_name,
                        "customer": customer,
                        "customerPhone": customer_phone
                    })

            return opened_tabs
        except (Exception,):
            show_messagebox(self.pos_id, "$ERROR_GET_OPENED_TABS")
            self.logger.exception("Error get opened tabs")
            raise StopAction()

    def show_opened_tabs(
            self,
            opened_tabs  # type: List[Dict]
    ):
        # type: (...) -> None

        order_options = []
        description_formatter = "{} # {} {} |True|{}|False"
        try:
            for tab in opened_tabs:
                description = description_formatter.format(
                    tab.get("name"),
                    tab.get("customer"),
                    tab.get("customerPhone"),
                    tab.get("tableId")
                )
                order_options.append((tab.get("tableId"), description, ""))

            buttons = "CANCEL|OPEN_TAB"
            title = "$SEARCH_OPENED_TABS"
            show_order_preview(self.pos_id, order_options, title, buttons=buttons, onthefly=True)

        except (Exception,):
            show_messagebox(self.pos_id, "$ERROR_GET_OPENED_TABS")
            self.logger.exception("Error show opened tabs")
            raise StopAction()

    @staticmethod
    def _is_tab(
            table  # type: Dict
    ):
        # type: (...) -> bool

        return table["typeDescr"] == "Tab" and table["id"].startswith('TAB')
