'use strict'

const config = require('config')
const Log = require('log')
const mongoose = require('mongoose')
const P = require('bluebird')

const PregnancyCenterModel = require('../pregnancy-centers/schema/mongoose-schema')

mongoose.Promise = require('bluebird')
const log = new Log('info')

const googleMapsClient = require('@google/maps').createClient({
	key: config.googleMaps.key,
	Promise: P,
})

// TODO: Error handling
const startDatabase = P.coroutine(function* startDatabase() {
	yield mongoose.connect(config.mongo.connectionString)

	log.info('Connected to database')
})

startDatabase()

// the longitude and latitute of PregnancyCenter are in pc.address.location, which is a GeoJSON point
// GeoJSON Point: { type: "Point", coordinates: [long, lat] }
//

// Google's geocoding API has the location part of the result in the format:
// "location" : {
//     "lat" : 37.4224764,
//     "lng" : -122.0842499
// }

async function geocodePregnancyCenters() {
	const pregnancyCenters = await PregnancyCenterModel.find({
		'address.location': null,
	})
	for (const pregnancyCenter of pregnancyCenters) {
		log.info(pregnancyCenter.prcName)
		log.info(pregnancyCenter.getFullAddress())

		// Geocode an address.
		const response = await googleMapsClient
			.geocode({ address: pregnancyCenter.getFullAddress() })
			.asPromise()
		const location = response.json.results[0].geometry.location

		log.info(location)

		pregnancyCenter.address.location = {
			type: 'Point',
			coordinates: [location.lng, location.lat],
		}
		await pregnancyCenter.save()
	}
	process.exit()
}

geocodePregnancyCenters()

@@ -1330,16 +1330,59 @@
 omise()%0A
+%09%09if (response.json.results.length %3E 0) %7B%0A%09
 %09%09const 
@@ -1436,16 +1436,17 @@
 cation%0A%0A
+%09
 %09%09log.in
@@ -1461,16 +1461,17 @@
 ion)%0A%0A%09%09
+%09
 pregnanc
@@ -1502,16 +1502,17 @@
  = %7B%0A%09%09%09
+%09
 type: 'P
@@ -1518,16 +1518,17 @@
 Point',%0A
+%09
 %09%09%09coord
@@ -1567,18 +1567,20 @@
 lat%5D,%0A%09%09
+%09
 %7D%0A
+%09
 %09%09await 
@@ -1602,16 +1602,20 @@
 .save()%0A
+%09%09%7D%0A
 %09%7D%0A%09proc

change geocode so that it doesn't error if there are no results (#135)