from datetime import datetime

import pytz

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


class WWFF(HTTPSpotProvider):
    """Spot provider for Worldwide Flora & Fauna"""

    POLL_INTERVAL_SEC = 120
    SPOTS_URL = "https://spots.wwff.co/static/spots.json"

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

    def _http_response_to_spots(self, http_response):
        new_spots = []
        # Iterate through source data
        for source_spot in http_response.json():
            # Convert to our spot format
            spot = Spot(source=self.name,
                        source_id=source_spot["id"],
                        dx_call=source_spot["activator"].upper(),
                        de_call=source_spot["spotter"].upper(),
                        freq=float(source_spot["frequency_khz"]) * 1000,
                        mode=source_spot["mode"].upper(),
                        comment=source_spot["remarks"],
                        sig="WWFF",
                        sig_refs=[SIGRef(id=source_spot["reference"], sig="WWFF", name=source_spot["reference_name"],
                                         latitude=source_spot["latitude"], longitude=source_spot["longitude"])],
                        time=datetime.fromtimestamp(source_spot["spot_time"], tz=pytz.UTC).timestamp(),
                        dx_latitude=source_spot["latitude"],
                        dx_longitude=source_spot["longitude"])

            # 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

    def can_submit_spot(self, sig):
        return sig == "WWFF"

    def submit_spot(self, spot, credentials):
        # TODO: Implement. Spotting to WWFF should be possible, need to look up the Spotline docs or copy approach from
        # PoLo. Either way I think we need an API key for the app (but maybe not for the user?)
        raise NotImplementedError("WWFF upstream spot submission is not yet implemented")
