import json
import logging

import geopandas
from shapely import prepare

from core.data_store import DATA_STORE
from providers.staticdata.local_file_static_data_provider import LocalFileStaticDataProvider


class CQZoneData(LocalFileStaticDataProvider):
    """Static data provider for CQ zone geodata."""

    PATH = "datafiles/cqzones.geojson"

    def __init__(self, provider_config):
        super().__init__("CQ Zone Data", provider_config, self.PATH)

    def _load_data(self, path):
        try:
            with open(path) as f:
                cq_zone_data = geopandas.GeoDataFrame.from_features(json.load(f)["features"])
            for idx in cq_zone_data.index:
                prepare(cq_zone_data.at[idx, 'geometry'])

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

            DATA_STORE.cq_zone_data = cq_zone_data
            return True

        except Exception as e:
            logging.error("Exception when loading CQ zone data.", e, exc_info=True)
            return False
