import importlib
import logging
import os

import yaml

# Check you have a config file
if not os.path.isfile("config.yml"):
    logging.error(
        "Your config file is missing. Ensure you have copied config-example.yml to config.yml and updated it according to your needs.")
    exit()

# Load config
with open("config.yml") as f:
    config = yaml.safe_load(f)
logging.info("Loaded config.")

BASE_URL = config.get("base_url", "http://localhost:8080")
MAX_SPOT_AGE = config.get("max_spot_age_sec", 3600)
MAX_ALERT_AGE = config.get("max_alert_age_sec", 604800)
SERVER_OWNER_CALLSIGN = config.get("server_owner_callsign", "N0CALL")
WEB_SERVER_PORT = config.get("web_server_port", 8080)
ALLOW_SPOTTING = config.get("allow_spotting", True)
ALLOW_UPSTREAM_SPOTTING = config.get("allow_upstream_spotting", True)
WEB_UI_OPTIONS = config.get("web_ui_options", {})
API_ONLY_MODE = config.get("api_only_mode", False)
RECAPTCHA_SECRET_KEY = config.get("recaptcha_secret_key", "")
RECAPTCHA_SITE_KEY = config.get("recaptcha_site_key", "")
LOG_LEVEL = config.get("log_level", "INFO")
LOG_WEB_REQUESTS = config.get("log_web_requests", False)

WEB_UI_OPTIONS["qrz_enabled"] = any(p["class"] == "QRZ" and p["enabled"] for p in config["callsign_data_providers"])
WEB_UI_OPTIONS["hamqth_enabled"] = any(p["class"] == "HamQTH" and p["enabled"] for p in config["callsign_data_providers"])
WEB_UI_OPTIONS["recaptcha_site_key"] = RECAPTCHA_SITE_KEY
WEB_UI_OPTIONS["allow_upstream_spotting"] = ALLOW_SPOTTING and ALLOW_UPSTREAM_SPOTTING


def create_provider_from_config(package, config_providers_entry):
    """Utility method to get a provider based on the class specified in its config entry. You must also provide the
    package to look for it in, as there are several types of provider. e.g. package "providers.spot", where the config
    entry is for a POTA spot provider."""

    module = importlib.import_module(package + "." + config_providers_entry["class"].lower())
    provider_class = getattr(module, config_providers_entry["class"])
    return provider_class(config_providers_entry)
