import logging

from core.data_store import DATA_STORE
from providers.staticdata.file_download_static_data_provider import FileDownloadStaticDataProvider


class K0SWE(FileDownloadStaticDataProvider):
    """Static data provider for K0SWE's dxcc.json, which provides callsign regex to DXCC entity mapping, plus DXCC to
    continent, flag emoji etc."""

    POLL_INTERVAL_DAYS = 7
    DATA_URL = "https://raw.githubusercontent.com/k0swe/dxcc-json/refs/heads/main/dxcc.json"

    def __init__(self, provider_config):
        super().__init__("K0SWE DXCC JSON", provider_config, self.DATA_URL, self.POLL_INTERVAL_DAYS)

    def _handle_http_response(self, http_response):
        try:
            dxcc_list = http_response.json()["dxcc"]
            # Reformat as a map for to place in the data store
            dxcc_map = {}
            for dxcc in dxcc_list:
                dxcc_map[dxcc["entityCode"]] = dxcc

                # Bail out if a stop has been requested, i.e. the program is shutting down - no need to parse the rest
                # of the data in this case
                if self._stop_event.is_set():
                    break

            # Add to data store
            # with transact() batches all writes together to save making thousands of individual sqlite writes
            with DATA_STORE.dxcc_data.transact():
                for k, v in dxcc_map.items():
                    DATA_STORE.dxcc_data.set(k, v)

                    if self._stop_event.is_set():
                        break

            # Regenerate in-memory regex-to-DXCC-entity-code map.
            DATA_STORE.regenerate_call_regex_to_dxcc_entity_map()

            return True

        except Exception as e:
            logging.error("Exception when loading K0SWE dxcc.json.", e, exc_info=True)
            return False


