import logging
from datetime import datetime

import pytz

from providers.alert.http_alert_provider import HTTPAlertProvider
from data.alert import Alert
from data.sig_ref import SIGRef


class ParksNPeaks(HTTPAlertProvider):
    """Alert provider for Parks n Peaks"""

    POLL_INTERVAL_SEC = 1800
    ALERTS_URL = "https://parksnpeaks.org/api/ALERTS/"

    def __init__(self, provider_config):
        super().__init__("ParksNPeaks", provider_config, self.ALERTS_URL, self.POLL_INTERVAL_SEC)

    def _http_response_to_alerts(self, http_response):
        new_alerts = []
        # Iterate through source data
        for source_alert in http_response.json():
            # Calculate some things
            sig = source_alert["Class"].upper()
            if " - " in source_alert["Location"]:
                split = source_alert["Location"].split(" - ")
                sig_ref = split[0]
                sig_ref_name = split[1]
            else:
                sig_ref = source_alert["WWFFID"]
                sig_ref_name = source_alert["Location"]
            start_time = datetime.strptime(source_alert["alTime"], "%Y-%m-%d %H:%M:%S").replace(
                tzinfo=pytz.UTC).timestamp()

            sigrefs = []
            # PnP can give us an alert of class "QRP" which is the only one that's not a real SIG in Spothole's list,
            # so mask this out if we got it.
            if sig != "QRP":
                sigrefs = [SIGRef(id=sig_ref, sig=sig, name=sig_ref_name)]

            # Convert to our alert format
            alert = Alert(source=self.name,
                          source_id=source_alert["alID"],
                          dx_calls=[source_alert["CallSign"].upper()],
                          freqs_modes=source_alert["Freq"] + " " + source_alert["MODE"],
                          comment=source_alert["Comments"],
                          sig_refs=sigrefs,
                          start_time=start_time,
                          is_dxpedition=False)

            # Log a warning for the developer if PnP gives us an unknown programme we've never seen before
            if sig and sig not in ["POTA", "SOTA", "WWFF", "SIOTA", "ZLOTA", "KRMNPA", "SANPCPA", "LLOTA", "QRP"]:
                logging.warning("PNP alert found with sig " + sig + ", developer needs to add support for this!")

            # If this is POTA, SOTA or WWFF data we already have it through other means, so ignore. Otherwise, add to
            # the alert list. Note that while ZLOTA has its own spots API, it doesn't have its own alerts API. So that
            # means the PnP *spot* provider rejects ZLOTA spots here, but the PnP *alerts* provider here allows ZLOTA.
            if sig not in ["POTA", "SOTA", "WWFF"]:
                new_alerts.append(alert)
        return new_alerts
