# -*- coding: utf-8 -*-

from sqlite3 import Connection

from msgbus import MBEasyContext
from old_helper import BaseRepository
from typing import List, Dict


class OrderRepository(BaseRepository):

    def __init__(
        self,
        mb_context,  # type: MBEasyContext
        pos_list,   # type: List[int]
    ):
        # type: (...) -> None
        super(OrderRepository, self).__init__(mb_context)
        self.pos_list = pos_list

    def get_orders_amount(
        self,
        order_ids,     # type: List[str]
    ):
        # type: (...) -> Dict
        orders = {}

        def inner_func(conn):
            # type: (Connection) -> Dict

            query = self._OrdersValueQuery.format(",".join(order_ids))
            for x in conn.select(query):
                order_id = x.get_entry("OrderId")
                amount = x.get_entry("TotalGross")
                tip = x.get_entry("Tip")
                if order_id not in orders:
                    orders[order_id] = {"amount": 0, "tip": 0}

                orders[order_id]["amount"] += float(amount)
                orders[order_id]["tip"] += float(tip)

            return orders

        self.execute_parallel_in_all_databases_returning_flat_list(inner_func, self.pos_list)
        return orders

    _OrdersValueQuery = """
        SELECT 
            OrderId,
            TotalGross,
            Tip
        FROM Orders
        WHERE OrderId in ({}) AND StateId IN (2, 3) 
    """
