import json
import logging

from helper import remove_accents
from old_helper import BaseRepository
from msgbus import MBEasyContext
from persistence import Connection
from typing import Dict

logger = logging.getLogger("FiscalWrapper")


class ProductRepository(BaseRepository):
    def __init__(self, mb_context):
        # type: (MBEasyContext) -> None

        super(ProductRepository, self).__init__(mb_context)

    def get_tender_types(self):
        # type: () -> Dict

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

            tender_types_dict = {}
            try:
                query = """SELECT TenderId, TenderDescr, CustomAttr FROM TenderType """

                for row in conn.select(query):
                    tender_id = row.get_entry("TenderId")
                    description = remove_accents(row.get_entry("TenderDescr"))
                    custom_attr = json.loads(row.get_entry("CustomAttr") or {})

                    tender_types_dict[description.upper()] = {
                        "tenderId": tender_id,
                        "description": description,
                    }

                    self._set_dict_tender_type(
                        custom_attr=custom_attr,
                        custom_attr_key="CNPJ",
                        tender_types_dict=tender_types_dict,
                        tender_types_dict_key="cnpj",
                        description=description,
                    )
                    self._set_dict_tender_type(
                        custom_attr=custom_attr,
                        custom_attr_key="clientId",
                        tender_types_dict=tender_types_dict,
                        tender_types_dict_key="clientId",
                        description=description,
                    )
                    self._set_dict_tender_type(
                        custom_attr=custom_attr,
                        custom_attr_key="tBand",
                        tender_types_dict=tender_types_dict,
                        tender_types_dict_key="tBand",
                        description=description,
                    )
                    self._set_dict_tender_type(
                        custom_attr=custom_attr,
                        custom_attr_key="tPag",
                        tender_types_dict=tender_types_dict,
                        tender_types_dict_key="tPag",
                        description=description,
                    )
                    self._set_dict_tender_type(
                        custom_attr=custom_attr,
                        custom_attr_key="cAdmC",
                        tender_types_dict=tender_types_dict,
                        tender_types_dict_key="cAdmC",
                        description=description,
                    )

                return tender_types_dict
            except (Exception,):
                logger.exception('Error to get tenders types')
                return tender_types_dict

        return self.execute_with_connection(inner_func)

    @ staticmethod
    def _set_dict_tender_type(
        custom_attr,                # type: Dict
        custom_attr_key,            # type: str
        tender_types_dict,          # type: Dict
        tender_types_dict_key,      # type: str
        description,                # type: str
    ):
        # type: (...) -> None

        custom_attr_value = custom_attr.get(custom_attr_key, None)

        if custom_attr_value:
            tender_types_dict[description.upper()][tender_types_dict_key] = str(custom_attr_value)
