import iso from "iso-3166-1";
/* global google */

export const GEOCODER = new google.maps.Geocoder();

export const reverseGeocode = async location => {
  try {
    const { results } = await GEOCODER.geocode({ location });
    // eslint-disable-next-line no-restricted-syntax
    for (const { address_components: comps } of results) {
      // eslint-disable-next-line no-restricted-syntax
      for (const { short_name: name, types } of comps) {
        if (types.indexOf("country") >= 0) {
          return name;
        }
      }
    }
  } catch (e) {
    // ignore errors - just use null
    // TODO probably alert the user?
  }
  return null;
};

const boundsCache = {};

export const getCountryBounds = async countryCode => {
  if (boundsCache[countryCode]) {
    return boundsCache[countryCode];
  }

  const { country } = iso.whereAlpha2(countryCode);
  try {
    const { results } = await GEOCODER.geocode({ address: country });
    // eslint-disable-next-line no-restricted-syntax
    for (const { geometry, types } of results) {
      if (geometry.viewport && types.indexOf("country") >= 0) {
        boundsCache[countryCode] = geometry.viewport;
        return geometry.viewport;
      }
    }
  } catch (e) {
    // ignore errors - just use null
    // TODO is there really no recovery from this?
  }
  return null;
};
