from datetime import datetime

import pytz

from alertproviders.http_alert_provider import HTTPAlertProvider
from core.sig_utils import get_icon_for_sig
from data.alert import Alert
from data.sig_ref import SIGRef


# Alert provider for Summits on the Air
class SOTA(HTTPAlertProvider):
    POLL_INTERVAL_SEC = 3600
    ALERTS_URL = "https://api-db2.sota.org.uk/api/alerts/365/all/all"

    def __init__(self, provider_config):
        super().__init__(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
            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=source_alert["summitDetails"])],
                          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
