from msgbus import MBEasyContext
from old_helper import BaseRepository
from persistence import Connection
from typing import (
    Dict,
    List,
    Tuple,
)


class FiscalParameterRepository(BaseRepository):

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

    def get_fiscal_parameters(
        self,           # type: FiscalParameterRepository
        loader_params,  # type: List[Dict[str, str]]
    ):
        # type: (...) -> Dict[Tuple[str, str], str]

        def inner_func(
            conn,   # type: Connection
        ):
            # type: (...) -> Dict[Tuple[int, str], str]

            query = "select ProductCode, ParamName, ParamValue from FiscalParameter"
            return {(str(x.get_entry(0)), x.get_entry(1)): x.get_entry(2) for x in conn.select(query)}

        fiscal_params = self.execute_with_connection(
            method=inner_func,
            service_name="FiscalPersistence",
        )

        if loader_params:
            for product in loader_params:
                product_code = product['PRODUCT_CODE']
                for param in product:
                    if param in ('PRODUCT_CODE', 'PRODUCT_NAME'):
                        continue
                    result = {(str(product_code), str(param)): str(product[param])}
                    fiscal_params.update(result)

        return fiscal_params
