import json
from datetime import datetime

from data.sig_ref import SIGRef
from data.spot import Spot
from providers.spot.http_spot_provider import HTTPSpotProvider


class Towers(HTTPSpotProvider):
    """Spot provider for Towers on the Air"""

    POLL_INTERVAL_SEC = 120
    SPOTS_URL = "https://wwtota.com/api/cluster_live.php"

    def __init__(self, provider_config):
        super().__init__("Towers", provider_config, self.SPOTS_URL, self.POLL_INTERVAL_SEC)

    def _http_response_to_spots(self, http_response):
        new_spots = []
        response_fixed = http_response.text.replace("\\/", "/")
        response_json = json.loads(response_fixed)

        # Iterate through source data
        for source_spot in response_json["spots"]:
            # Convert to our spot format
            likely_freq = float(source_spot["freq"]) * 1000
            if likely_freq < 1000000:
                likely_freq = likely_freq * 1000
            spot = Spot(source=self.name,
                        dx_call=source_spot["call"].upper(),
                        freq=likely_freq,
                        comment=source_spot["comment"],
                        sig="Towers",
                        sig_refs=[SIGRef(id=source_spot["ref"], sig="Towers")],
                        time=datetime.strptime(response_json["updated"][:10] + source_spot["time"],
                                               "%Y-%m-%d%H:%M").timestamp())

            # Add to our list. Don't worry about de-duping, removing old spots etc. at this point; other code will do
            # that for us.
            new_spots.append(spot)
        return new_spots
