import json

from old_helper import BaseRepository
from persistence import Connection
from typing import List

from justificationdiscountreport.model import JustificationDiscount


class JustificationDiscountRepository(BaseRepository):

    def __init__(
        self,
        mb_context,
        pos_id,
    ):
        # type: (...) -> None

        super(JustificationDiscountRepository, self).__init__(mb_context)

        self.pos_id = pos_id

    def get_justifications(
        self,
        initial_date,       # type: str
        end_date,           # type: str
        operator_id,        # type: str
    ):
        # type: (...) -> List[JustificationDiscount]

        def inner_func(
            conn,    # type: Connection
        ):
            # type: (...) -> List[JustificationDiscount]

            query = self._OrdersQuery.format(initial_date, end_date)
            result = []
            for row in conn.select(query):
                benefit_list_json = json.loads(row.get_entry("BenefitList"))
                benefit_list = json.loads(benefit_list_json.get("benefitList", None))
                for benefit_item in benefit_list:

                    benefit = benefit_item.get("benefit")
                    request_justification = benefit.get("requestJustification")
                    justification = benefit.get("justification", None)

                    if not request_justification or justification in ['', None]:
                        continue

                    applied_by = benefit.get("appliedBy", "")

                    if operator_id is not None and operator_id != applied_by:
                        continue

                    benefit_id = benefit_item.get("benefit_id", "")
                    benefit_total_value = benefit_item.get("benefit_total_value", 0)

                    result.append(
                        JustificationDiscount(
                            row_database=row,
                            benefit_id=benefit_id,
                            justification=justification,
                            applied_by=applied_by,
                            benefit_total_value=benefit_total_value,
                        )
                    )

            return result

        return self.execute_parallel_in_all_databases_returning_flat_list(inner_func, self.pos_id)

    _OrdersQuery = """
                        SELECT o.OrderId,
                               o.TotalGross,
                               od.OrderDate,
                               od.OrderTime,
                               ocp.Value AS BenefitList
                         FROM Orders o
                         INNER JOIN OrderCustomProperties ocp ON ocp.OrderId = o.OrderId AND ocp.Key = 'BENEFIT_LIST'
                         INNER JOIN (
                                    SELECT OrderId, 
                                           strftime('%Y-%m-%d', max(Timestamp) , 'localtime') OrderDate,
                                           strftime('%H:%M:%S', max(Timestamp), 'localtime') OrderTime
                                      FROM OrderStateHistory
                                     WHERE StateId = 5
                                     GROUP BY OrderId
                                ) od on o.OrderId = od.OrderId
                         WHERE 
                            o.BusinessPeriod >= '{0}' 
                            AND o.BusinessPeriod <= '{1}' 
                            AND o.StateId = 5
                         GROUP by o.OrderId, o.BusinessPeriod
                         ORDER BY o.OrderId, o.BusinessPeriod
                      """
