from core.data_providers import DATA_PROVIDERS
from data.callsign import Callsign


def get_call_info(callsign, lookup_credentials):
    """Utility method to get the best set of data for a callsign as we can, using all enabled providers.
    lookup_credentials is an optional object that carries the user's QRZ.com/HamQTH credentials, if they provided them,
    to enable lookup using those providers."""

    callsign_data = Callsign(call=callsign)

    if callsign:
        # Sort callsign providers by priority order, so we query the highest priority (lowest numbers) first, and only
        # query other providers for data we are missing as we go along.
        for p in sorted(DATA_PROVIDERS.callsign_data_providers, key=lambda p: p.priority):
            if p.enabled:
                # Get new lookup data
                data = p.lookup(callsign, lookup_credentials)
                if data:
                    # If we have new data for fields that were previously unpopulated, add them in
                    for key, value in data.__dict__.items():
                        if value is not None and callsign_data.__dict__.get(key) is None:
                            callsign_data.__dict__[key] = value

                    # If callsign data is fully populated, avoid looking up using other providers as their data will not
                    # be used
                    if callsign_data.fully_populated():
                        break

    return callsign_data