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 SOTA(HTTPAlertProvider):
    """Alert provider for Summits on the Air"""

    POLL_INTERVAL_SEC = 1800
    ALERTS_URL = "https://api-db2.sota.org.uk/api/alerts/365/all/all"

    def __init__(self, provider_config):
        super().__init__("SOTA", 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():
            # Convert to our alert format
            details = source_alert["summitDetails"].split(", ")
            summit_name = details[0]
            summit_points = None
            if len(details) > 2:
                summit_points = int(details[-1].split(" ")[0])
            alert = Alert(source=self.name,
                          source_id=source_alert["id"],
                          dx_calls=[source_alert["activatingCallsign"].upper()],
                          dx_names=[source_alert["activatorName"].upper()],
                          freqs_modes=source_alert["frequency"],
                          comment=source_alert["comments"],
                          sig_refs=[
                              SIGRef(id=source_alert["associationCode"] + "/" + source_alert["summitCode"], sig="SOTA",
                                     name=summit_name, activation_score=summit_points)],
                          start_time=datetime.strptime(source_alert["dateActivated"],
                                                       "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=pytz.UTC).timestamp(),
                          is_dxpedition=False)

            # Add to our list
            new_alerts.append(alert)
        return new_alerts
