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)
