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

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

from dailygoals_services.model import OrderItem
from dailygoals_services.model.repository import ProductRepository as ProductRepositoryRepository


class ProductRepository(
    ProductRepositoryRepository,
    BaseRepository,
):

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

        super(ProductRepository, self).__init__(mb_context)

    def get_order_items_names(
        self,
        order_items,    # type: List[OrderItem]
    ):
        # type: (...) -> List[OrderItem]

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

            query = self._ProductNamesQuery
            prod_codes_list = map(lambda order: order.pcode, order_items)
            prod_codes_list = ','.join(map(str, prod_codes_list))
            query = query.format(prod_codes_list)

            product_names = [(int(x.get_entry(0)), x.get_entry(1)) for x in conn.select(query)]
            for product_tuple in product_names:
                for order_item in order_items:
                    if product_tuple[0] == order_item.pcode:
                        order_item.name = product_tuple[1]
            return order_items

        return self.execute_with_connection(method=inner_func)

    _ProductNamesQuery = """\
    SELECT *
    FROM Product
    WHERE ProductCode IN ({0})
    """