import re
from time import sleep

from fastkml import kml
from pyhamtools.locator import latlong_to_locator

from data.sig_ref import SIGRef
from providers.sigrefdata.file_download_sig_ref_data_provider import FileDownloadSIGRefDataProvider


class ParksNPeaksKMLSIGRefDataProvider(FileDownloadSIGRefDataProvider):
    """Base class for SIG ref data providers that use parksnpeaks.org KML POI feeds and have references that use the
    VKFF refs rather than their own system (i.e. KRMNPA and SANPCPA)."""

    REF_PATTERN = re.compile(r"VKFF-\d+")

    def __init__(self, sig_name, provider_config, url, poll_interval):
        """ Set up the provider, note poll_interval is in *days*."""
        super().__init__(sig_name, provider_config, url, poll_interval)

    def _http_response_to_data(self, http_response):
        new_data = []

        k = kml.KML.from_string(http_response.content)

        for document in k.features:
            for folder in document.features:
                for placemark in folder.features:
                    description = placemark.description or ""
                    match = self.REF_PATTERN.search(description)
                    if not match:
                        # No VKFF reference found in this placemark - skip it (e.g. non-park waypoints)
                        continue
                    ref_id = match.group(0)

                    longitude, latitude = placemark.geometry.x, placemark.geometry.y

                    ref = SIGRef(sig=self.sig_name, id=ref_id, name=placemark.name,
                                              ref_type="Park",
                                              url="https://parksnpeaks.org/getPark.php?actPark=" + ref_id,
                                              latitude=latitude,
                                              longitude=longitude)
                    if latitude and longitude:
                        ref.grid = latlong_to_locator(latitude, longitude, 6)
                    new_data.append(ref)

                    # 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():
                        return new_data

                    # Very short pause. This will extend the time to handle sig refs by a few seconds but will ensure some time
                    # is available for other threads e.g. the web server.
                    sleep(0.001)

        return new_data
