# -*- coding: utf-8 -*-

from manager.reports import opened_tables_report
from sysactions import show_messagebox
from pos_model import TableStatus
from xml.etree import cElementTree as eTree


def show_open_table_dialog(pos_id):
    ret = show_messagebox(pos_id, "$NEED_TO_CLOSE_ALL_TABLES_AND_TABS", buttons="$YES|$NO")
    if ret == 0:
        opened_tables_report(pos_id)


def has_tab_or_tables_opened(period, pos_id, operator_id=None):
    from msgbusboundary import MsgBusTableService as tableService
    from table_actions import has_table_service

    if not has_table_service():
        return False

    all_tables = tableService().list_tables(pos_id)

    for table in all_tables:
        if table.business_period != int(period):
            continue

        if not _is_open(table):
            continue

        if operator_id:
            table_picture = eTree.XML(tableService().get_table_picture(pos_id, table.id))
            table_user_id = table_picture.get("userId")
            if table_user_id != operator_id:
                continue
            return True

        return True

    return False


def _is_open(table):
    if "TAB" in table.id:
        is_open = int(table.status) not in [TableStatus.AVAILABLE, TableStatus.CLOSED]
    else:
        is_open = int(table.status) != TableStatus.AVAILABLE

    return is_open


def table_is_totaled(table):
    return table.status == TableStatus.TOTALIZED

