import csv
import logging

from pyhamtools.locator import latlong_to_locator

from core.cache_utils import SEMI_STATIC_URL_DATA_CACHE
from core.constants import SIGS, HTTP_HEADERS
from core.geo_utils import wab_wai_square_to_lat_lon
from data.sig_ref import SIGRef


# Utility function to get the icon for a named SIG. If no match is found, the "circle-question" icon will be returned.
def get_icon_for_sig(sig):
    for s in SIGS:
        if s.name == sig:
            return s.icon
    return "circle-question"


# Utility function to get the regex string for a SIG reference for a named SIG. If no match is found, None will be returned.
def get_ref_regex_for_sig(sig):
    for s in SIGS:
        if s.name.upper() == sig.upper():
            return s.ref_regex
    return None


# Look up details of a SIG reference (e.g. POTA park) such as name, lat/lon, and grid.
# Note there is currently no support for KRMNPA location lookup, see issue #61.
def get_sig_ref_info(sig, sig_ref_id):
    sig_ref = SIGRef(id=sig_ref_id, sig=sig)
    try:
        if sig.upper() == "POTA":
            data = SEMI_STATIC_URL_DATA_CACHE.get("https://api.pota.app/park/" + sig_ref_id, headers=HTTP_HEADERS).json()
            if data:
                fullname = data["name"] if "name" in data else None
                if fullname and "parktypeDesc" in data and data["parktypeDesc"] != "":
                    fullname = fullname + " " + data["parktypeDesc"]
                sig_ref.name = fullname
                sig_ref.url = "https://pota.app/#/park/" + sig_ref_id
                sig_ref.grid = data["grid6"] if "grid6" in data else None
                sig_ref.latitude = data["latitude"] if "latitude" in data else None
                sig_ref.longitude = data["longitude"] if "longitude" in data else None
        elif sig.upper() == "SOTA":
            print(sig_ref_id)
            data = SEMI_STATIC_URL_DATA_CACHE.get("https://api-db2.sota.org.uk/api/summits/" + sig_ref_id,
                                                  headers=HTTP_HEADERS).json()
            if data:
                sig_ref.name = data["name"] if "name" in data else None
                sig_ref.url = "https://www.sotadata.org.uk/en/summit/" + sig_ref_id
                sig_ref.grid = data["locator"] if "locator" in data else None
                sig_ref.latitude = data["latitude"] if "latitude" in data else None
                sig_ref.longitude = data["longitude"] if "longitude" in data else None
        elif sig.upper() == "WWBOTA":
            data = SEMI_STATIC_URL_DATA_CACHE.get("https://api.wwbota.org/bunkers/" + sig_ref_id,
                                                  headers=HTTP_HEADERS).json()
            if data:
                sig_ref.name = data["name"] if "name" in data else None
                sig_ref.url = "https://bunkerwiki.org/?s=" + sig_ref_id if sig_ref_id.startswith("B/G") else None
                sig_ref.grid = data["locator"] if "locator" in data else None
                sig_ref.latitude = data["lat"] if "lat" in data else None
                sig_ref.longitude = data["long"] if "long" in data else None
        elif sig.upper() == "GMA" or sig.upper() == "ARLHS" or sig.upper() == "ILLW" or sig.upper() == "WCA" or sig.upper() == "MOTA" or sig.upper() == "IOTA":
            data = SEMI_STATIC_URL_DATA_CACHE.get("https://www.cqgma.org/api/ref/?" + sig_ref_id,
                                                  headers=HTTP_HEADERS).json()
            if data:
                sig_ref.name = data["name"] if "name" in data else None
                sig_ref.url = "https://www.cqgma.org/zinfo.php?ref=" + sig_ref_id
                sig_ref.grid = data["locator"] if "locator" in data else None
                sig_ref.latitude = data["latitude"] if "latitude" in data else None
                sig_ref.longitude = data["longitude"] if "longitude" in data else None
        elif sig.upper() == "WWFF":
            sig_ref.url = "https://wwff.co/directory/?showRef=" + sig_ref_id
        elif sig.upper() == "SIOTA":
            siota_csv_data = SEMI_STATIC_URL_DATA_CACHE.get("https://www.silosontheair.com/data/silos.csv",
                                                            headers=HTTP_HEADERS)
            siota_dr = csv.DictReader(siota_csv_data.content.decode().splitlines())
            for row in siota_dr:
                if row["SILO_CODE"] == sig_ref_id:
                    sig_ref.name = row["NAME"] if "NAME" in row else None
                    sig_ref.grid = row["LOCATOR"] if "LOCATOR" in row else None
                    sig_ref.latitude = float(row["LAT"]) if "LAT" in row else None
                    sig_ref.longitude = float(row["LNG"]) if "LNG" in row else None
        elif sig.upper() == "WOTA":
            data = SEMI_STATIC_URL_DATA_CACHE.get("https://www.wota.org.uk/mapping/data/summits.json",
                                                  headers=HTTP_HEADERS).json()
            if data:
                for feature in data["features"]:
                    if feature["properties"]["wotaId"] == sig_ref_id:
                        sig_ref.name = feature["properties"]["title"]
                        sig_ref.url = "https://www.wota.org.uk/MM_" + sig_ref_id
                        sig_ref.grid = feature["properties"]["qthLocator"]
                        sig_ref.latitude = feature["geometry"]["coordinates"][1]
                        sig_ref.longitude = feature["geometry"]["coordinates"][0]
        elif sig.upper() == "ZLOTA":
            data = SEMI_STATIC_URL_DATA_CACHE.get("https://ontheair.nz/assets/assets.json", headers=HTTP_HEADERS).json()
            if data:
                for asset in data:
                    if asset["code"] == sig_ref_id:
                        sig_ref.name = asset["name"]
                        sig_ref.url = "https://ontheair.nz/assets/ZLI_OT-030" + sig_ref_id.replace("/", "_")
                        sig_ref.grid = latlong_to_locator(asset["y"], asset["x"], 6)
                        sig_ref.latitude = asset["y"]
                        sig_ref.longitude = asset["x"]
        elif sig.upper() == "BOTA":
            if not sig_ref.name:
                sig_ref.name = sig_ref.id
            sig_ref.url = "https://www.beachesontheair.com/beaches/" + sig_ref.name.lower().replace(" ", "-")
        elif sig.upper() == "WAB" or sig.upper() == "WAI":
            ll = wab_wai_square_to_lat_lon(sig_ref_id)
            if ll:
                sig_ref.name = sig_ref_id
                sig_ref.grid = latlong_to_locator(ll[0], ll[1], 6)
                sig_ref.latitude = ll[0]
                sig_ref.longitude = ll[1]
    except:
        logging.warn("Failed to look up sig_ref info for SIG " + sig + " ref " + sig_ref_id + ".")
    return sig_ref


# Regex matching any SIG
ANY_SIG_REGEX = r"(" + r"|".join(list(map(lambda p: p.name, SIGS))) + r")"

# Regex matching any SIG reference
ANY_XOTA_SIG_REF_REGEX = r"[\w\/]+\-\d+"
