from typing import List, Tuple, Union, Dict
import collections
import logging

import aiohttp

from ..schemas import GenMethodEnum, CountryCode

geonames_user = "terrassumptions"
geonames_url = "http://api.geonames.org/countryCodeJSON"

# Google API key, with access to Street View Static API
# this can be safely committed due to permission restriction
google_api_key = "AIzaSyAqjCYR6Szph0X0H_iD6O1HenFhL9jySOo"
metadata_url = "https://maps.googleapis.com/maps/api/streetview/metadata"

logger = logging.getLogger(__name__)

aiohttp_client = aiohttp.ClientSession()


async def point_has_streetview(lat, lng):
    """
    Returns True if the streetview metadata endpoint says a given point has
    data available, and False otherwise.

    This function calls the streetview metadata endpoint - there is no quota consumed.
    """
    params = {
        "key": google_api_key,
        "location": f"{lat},{lng}",
    }
    async with aiohttp_client.get(metadata_url, params=params) as response:
        body = await response.json()
        return body["status"] == "OK"


async def reverse_geocode(lat, lng):
    params = {
        "lat": str(lat),
        "lng": str(lng),
        "username": geonames_user,
    }
    try:
        async with aiohttp_client.get(geonames_url, params=params) as response:
            body = await response.json()
            country_code = body.get("countryCode", None)
            if country_code is not None:
                country_code = country_code.lower()
            return country_code
    except:
        logger.exception("Failed to reverse geocode! Hopefully this isn't a guess and the generator data is accurate...")
        return None
