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) -> Dict
            res = {}
            try:
                query = """SELECT TenderId, TenderDescr, CustomAttr FROM TenderType """

                for row in conn.select(query):
                    custom_attr = row.get_entry("CustomAttr")
                    if custom_attr in ['', None] or "tBand" not in custom_attr:
                        continue

                    tender_id = row.get_entry("TenderId")
                    description = remove_accents(row.get_entry("TenderDescr"))
                    custom_attr = json.loads(custom_attr)

                    res[description.upper()] = {
                        "tenderId": tender_id,
                        "description": description,
                        "cnpj": str(custom_attr.get("CNPJ", None)),
                        "clientId": str(custom_attr.get("clientId", None)),
                        "tBand": str(custom_attr.get("tBand", None)),
                        "tPag": str(custom_attr.get("tPag", None)),
                        "cAdmC": str(custom_attr.get("cAdmC", None)),
                    }

                return res
            except Exception as _:
                logger.exception('Error to get tenders types')
                return res

        return self.execute_with_connection(inner_func)

