# encoding: utf-8
from old_helper import BaseRepository

from openedtablesreport.model import OpenedTable


class TableRepository(BaseRepository):

    def __init__(self, mbcontext, pos_id):
        super(TableRepository, self).__init__(mbcontext)
        self.pos_id = pos_id

    def get_opened_tables(self):
        # type: (...) -> OpenedTable

        def inner_func(conn):
            query = self._OpenedTablesQuery
            tables = {}
            for x in conn.select(query):
                table_id = x.get_entry("TableId")
                table_status = x.get_entry("Status")
                split_order_id = x.get_entry("SplitOrderId")
                order_id = x.get_entry("OrderId")

                if table_status == "TOTALED":
                    if split_order_id is None:
                        continue

                    order_id = split_order_id
                else:
                    if split_order_id is not None:
                        continue

                if table_id not in tables:
                    tables[table_id] = OpenedTable(
                        table_id=table_id,
                        name=x.get_entry("TableName"),
                        sector=x.get_entry("Sector"),
                        opened_date=x.get_entry("StartTS"),
                        status=table_status,
                        operator=x.get_entry("UserId"),
                        seats=x.get_entry("NumberOfSeats"),
                    )

                if order_id not in tables[table_id].orders:
                    tables[table_id].orders.append(order_id)

            return tables

        return self.execute_with_connection(inner_func)

    _OpenedTablesQuery = """
        SELECT DISTINCT
            rt.TableId,
            COALESCE(scp.PropertyValue, rt.TableName, rt.TableId) AS TableName,
            rt.sector,
            ts.StartTS,
            UPPER(ts.Descr) AS Status,
            ts.UserId,
            ts.NumberOfSeats,
            so.OrderId,
            ss.SplitOrderId
        FROM TableService ts
        LEFT JOIN ServiceOrders so ON so.ServiceId = ts.ServiceId AND so.state != 'IN_PROGRESS'
        JOIN RestaurantTable rt ON ts.TableId = rt.TableId
        LEFT JOIN ServiceSplit ss ON ts.ServiceId = ss.ServiceId AND so.OrderId = ss.OrderId
        JOIN TableStatus ts ON rt.Status = ts.Status
        LEFT JOIN ServiceCustomProperty scp ON ts.ServiceId = scp.ServiceId AND scp.PropertyKey = 'TAB_ID'
        WHERE ts.FinishedTS IS NULL
    """
