import logging
from datetime import datetime

import pytz
from pyhamtools import LookupLib, Callinfo

from core.data_store import DATA_STORE
from core.utils import get_callsign_object_from_pyhamtools_callinfo
from data.callsign import Callsign
from providers.callsigndata.api_query_callsign_data_provider import APIQueryCallsignDataProvider


class ClublogAPI(APIQueryCallsignDataProvider):
    """Callsign data provider for Clublog's API."""

    _callinfo = None

    def __init__(self, provider_config):
        # API key required for this provider
        self._api_key = provider_config.get("api_key", "")
        if self._api_key != "":
            lookuplib = LookupLib(lookuptype="clublogapi", apikey=self._api_key)
            self._callinfo = Callinfo(lookuplib)
        else:
            provider_config["enabled"] = False
            logging.warning(
                "Clublog XML callsign data provider configured but no api key was provided, this has been disabled.")

        super().__init__("Clublog API", provider_config, DATA_STORE.callsign_data_clublogapi)


    def _perform_new_lookup(self, callsign, lookup_credentials):
        callsign_data = Callsign(call=callsign)

        try:
            if self._callinfo:
                callsign_data = get_callsign_object_from_pyhamtools_callinfo(callsign, self._callinfo)
                self.status = "OK"
                self.last_update_time = datetime.now(pytz.UTC)
                self.lookup_count += 1
            else:
                return None

        except Exception as e:
            self.status = "Error"
            logging.error("Exception when looking up data from Clublog API", e, exc_info=True)

        return callsign_data
