import json

from old_helper import BaseRepository
from typing import List, Optional

class OrderRepository(BaseRepository):
    def __init__(self, mb_context):
        super(OrderRepository, self).__init__(mb_context)

    def get_orders_benefit(self, initial_date, end_date, operator_id, pos_list):
        # type: (str, str, Optional[str], List[int]) -> List

        def inner_func(conn):

            query_operator = " and SessionId like '%user={0},%'".format(operator_id) if operator_id is not None else ""
            query = """SELECT o.OrderId, ocp.Value as BenefitList
                         FROM Orders o
                        INNER JOIN OrderTender ot
                           ON o.OrderId = ot.OrderId
                        INNER JOIN OrderCustomProperties ocp
                           ON ocp.OrderId = o.OrderId AND ocp.Key = 'BENEFIT_LIST'
                        WHERE o.BusinessPeriod >= '{0}' AND o.BusinessPeriod <= '{1}' AND o.StateId = 5
                        {2}
                        GROUP by o.OrderId
                        """.format(initial_date, end_date, query_operator)

            benefits = []
            cursor = conn.select(query)
            if cursor.rows() > 0:
                for row in cursor:
                    benefit_list_json = json.loads(row.get_entry("BenefitList"))
                    benefit_list_json = json.loads(benefit_list_json.get("benefitList", None))
                    for benefit in benefit_list_json:
                        benefit_applied = benefit.get("benefit_applied", False)
                        benefit_total_value = benefit.get("benefit_total_value", 0)
                        if not benefit_applied or benefit_total_value == 0:
                            continue
                        benefits.append(benefit)

            return benefits

        return self.execute_in_all_databases_returning_flat_list(inner_func, pos_list)

    def get_fiscalized_orders(
            self,
            from_date,  # type: str
            pos_list,   # type: List[int]
    ):
        # type: (...) -> List

        def inner_func(conn):
            query = """
               SELECT 
                    o.OrderId AS OrderId, 
                    ocp.Value AS FiscalizationDate, 
                    o.DistributionPoint AS PodType, 
                    O.OriginatorId AS OriginatorId, 
                    o.TotalGross AS TotalGross,
                    o.Tip AS Tip
               FROM Orders o
               JOIN OrderCustomProperties ocp ON 
                    o.OrderId = ocp.OrderId AND 
                    ocp.Key = 'FISCALIZATION_DATE'
                WHERE 
                    StateId = 5 AND
                    DATETIME(ocp.Value) >= DATETIME('{}')
            """.format(from_date)

            orders = []
            cursor = conn.select(query)
            if cursor.rows() > 0:
                for row in cursor:
                    fiscalized_order = FiscalizedOrder(
                        order_id=row.get_entry("OrderId"),
                        fiscalization_date=row.get_entry("FiscalizationDate"),
                        pod_type=row.get_entry("PodType"),
                        originator_id=row.get_entry("OriginatorId"),
                        total_gross=row.get_entry("TotalGross"),
                        tip=row.get_entry("Tip"),
                    )
                    orders.append(fiscalized_order)

            return orders

        return self.execute_in_all_databases_returning_flat_list(inner_func, pos_list)


class FiscalizedOrder(object):
    def __init__(
            self,
            order_id,               # type: str
            fiscalization_date,     # type: str
            pod_type,               # type: str
            originator_id,          # type: str
            total_gross,            # type: str
            tip,                    # type: str
    ):
        # type: (...) -> None
        self.order_id = order_id
        self.fiscalization_date = fiscalization_date
        self.pod_type = pod_type
        self.originator_id = originator_id
        self.total_gross = total_gross
        self.tip = tip
