import P from 'bluebird'
import { GET_PREGNANCY_RESOURCE_CENTERS } from './action-types'

import { store } from '../../hah-app'

function getPregnancyResourceCentersAction(pregnancyResourceCenters) {
	return {
		type: GET_PREGNANCY_RESOURCE_CENTERS,
		pregnancyResourceCenters,
	}
}

export const getPregnancyResourceCenters = address => {
	return function(dispatch) {
		return findPregnancyResourceCentersNearMe(address).then(result =>
			dispatch(getPregnancyResourceCentersAction(result)),
		)
	}
}

async function findPregnancyResourceCentersNearMe(address) {
	const miles = 50

	const coordinates = await geocodeAddress(address)
	const { lat, lng } = coordinates

	const queryString = `?lng=${lng}&lat=${lat}&miles=${miles}`
	const fullUrl = `/api/pregnancy-centers/near-me${queryString}`

	const response = await fetch(fullUrl, {
		method: 'GET',
	})

	return await response.json()
}

async function geocodeAddress(address) {
	const googleMapsClient = require('@google/maps').createClient({
		key: store.getState().initialData.googleMapsApiKey,
		Promise: P,
	})

	const response = await googleMapsClient.geocode({ address }).asPromise()

	return response.json.results[0].geometry.location
}

@@ -1,29 +1,4 @@
-import P from 'bluebird'%0A
 impo
@@ -912,72 +912,100 @@
 st g
-oogleMapsClient = require('@google/maps').createClient(%7B%0A%09%09key: 
+eocodeURL = %60https://maps.googleapis.com/maps/api/geocode/json?address=$%7Baddress%7D&key= $%7B%0A%09%09
 stor
@@ -1049,28 +1049,12 @@
 iKey
-,%0A%09%09Promise: P,
 %0A%09%7D
-)%0A
+%60
 %0A%09co
@@ -1078,67 +1078,94 @@
 ait 
-googleMapsClient.geocode(%7B address %7D).asPromise
+fetch(geocodeURL, %7B%0A%09%09method: 'GET',%0A%09%7D)%0A%0A%09const json = await response.json
 ()%0A
-%0A
 %09return 
 resp
@@ -1160,25 +1160,16 @@
 %09return 
-response.
 json.res

Fix Safari Google Maps Error: "Failed to Load Resource" (#205)