from decimal import Decimal

from msgbus import MBEasyContext
from old_helper import BaseRepository
from persistence import Connection
from sysactions import get_poslist
from typing import Tuple


class DrawerRepository(BaseRepository):
    def __init__(
            self,
            mb_context,     # type: MBEasyContext
    ):
        # type: (...) -> None

        super(DrawerRepository, self).__init__(mb_context)
        self.pos_list = get_poslist()

    def get_user_sum_cash_values(
            self,
            period,     # type: str
            session,    # type: str
    ):
        # type: (...) -> Tuple[Decimal, Decimal]

        cash_gross = []
        cash_refund = []

        def inner_func(
                conn    # type: Connection
        ):
            # type: (...) -> None

            query = """
                        SELECT
                            tdsub(
                                    tdsum(DA.SaleCashAmount), 
                                    COALESCE(tdsum(DA.SaleCashChangeAmount), 0)
                                ) AS CashGrossAmount,
                            tdsum(DA.RefundCashAmount) AS RefundCashAmount
                        FROM (
                            SELECT
                                tdsum(
                                    CASE WHEN (Orders.OrderType=0 AND OrderTender.TenderId=0) 
                                        THEN OrderTender.ChangeAmount 
                                        ELSE '0.00' END
                                    ) AS SaleCashChangeAmount,
                                tdsum(
                                    CASE WHEN (Orders.OrderType=0 AND OrderTender.TenderId=0) 
                                        THEN OrderTender.TenderAmount 
                                        ELSE '0.00' END
                                    ) AS SaleCashAmount,
                                COALESCE(
                                    tdsum(
                                        CASE WHEN (OrderTender.TenderId=0 AND Orders.OrderType=1) 
                                            THEN tdsub(OrderTender.TenderAmount,COALESCE(OrderTender.ChangeAmount,'0')) 
                                            ELSE '0.00' END
                                        ),'0.00') AS RefundCashAmount
                            FROM orderdb.Orders Orders
                            JOIN orderdb.OrderTender OrderTender ON OrderTender.OrderId=Orders.OrderId
                            WHERE Orders.StateId=5 AND Orders.OrderType IN (0,1)
                            AND substr(Orders.SessionID, instr(Orders.SessionID, 'period=')+7) = '{}'
                            AND Orders.SessionID = '{}'
                            GROUP BY Orders.BusinessPeriod, Orders.SessionId, Orders.OrderId
                        ) AS DA
                    """.format(period, session)

            for x in conn.select(query):
                cash_gross.append(Decimal(x.get_entry("CashGrossAmount") or 0))
                cash_refund.append(Decimal(x.get_entry("RefundCashAmount") or 0))

        self.execute_parallel_in_all_databases(inner_func, self.pos_list)

        return sum(cash_gross), sum(cash_refund)
