const P = require('bluebird')
const config = require('config')
const fetch = require('node-fetch')
const querystring = require('querystring')
const { firebase } = require('../../firebase')
const graphData = require('../../graph/data')
const processMap = require('../process-map')

const db = firebase.database().ref()

module.exports = ({ data, resolve, reject }) => {
  const { from, to, latitude, longitude, timestamp } = data

  return P.coroutine(function* setConnection() {

    const qs = querystring.stringify({
      lat: latitude,
      lng: longitude,
      username: config.geonames.username,
      cities: 'cities15000',
    })

    const locationData = yield fetch(`http://api.geonames.org/findNearbyPlaceNameJSON?${qs}`)
      .then(res => res.json())
    const { name, countryName } = locationData

    const connectionKey = [from, to].join('::::')
    const connection = {
      from,
      latitude,
      longitude,
      timestamp,
      to,
      city: name,
      country: countryName,
    }

    // Set the connection entry
    yield db.child(`connections/${connectionKey}`).set(connection)

    // Set the connection and set hasAccess true on both user objects
    const fromUpdate = {
      [`connections/${to}`]: to,
      hasAccess: true,
    }

    const toUpdate = {
      [`connections/${from}`]: from,
      hasAccess: true,
      from,
    }

    yield P.props({
      to: db.child(`users/${from}`).update(fromUpdate),
      from: db.child(`users/${to}`).update(toUpdate),
    })

    // Now remove the beacons
    yield P.props({
      removeBeaconFrom: db.child(`beacons/${from}`).set(null),
      removeBeaconLocationFrom: db.child(`beaconLocations/${from}`).set(null),
      removeBeaconTo: db.child(`beacons/${to}`).set(null),
      removeBeaconLocationTo: db.child(`beaconLocations/${to}`).set(null),
    })

    // Update the internal graph
    graphData.setConnection(connection)

    // Update the map representation
    yield processMap()

  })().then(resolve).catch((err) => {
    const message = {
      type: 'CONNECTION_FAILED',
      timestamp: Date.now(),
    }

    // Set the failed messages to both connecting users
    return P.props({
      to: db.child(`messages/${to}/${from}`).set(message),
      from: db.child(`messages/${from}/${to}`).set(message),
    }).then(() => {
      return reject(err)
    })
  })
}

@@ -1,12 +1,74 @@
+const _ = require('lodash')%0Aconst logger = require('winston')%0A
 const P = re
@@ -85,16 +85,16 @@
 ebird')%0A
-
 const co
@@ -821,16 +821,68 @@
 json())%0A
+      .then(data =%3E _.get(data, 'geonames.0', %7B%7D))%0A%0A
     cons
@@ -1623,342 +1623,8 @@
 %7D)%0A%0A
-    // Now remove the beacons%0A    yield P.props(%7B%0A      removeBeaconFrom: db.child(%60beacons/$%7Bfrom%7D%60).set(null),%0A      removeBeaconLocationFrom: db.child(%60beaconLocations/$%7Bfrom%7D%60).set(null),%0A      removeBeaconTo: db.child(%60beacons/$%7Bto%7D%60).set(null),%0A      removeBeaconLocationTo: db.child(%60beaconLocations/$%7Bto%7D%60).set(null),%0A    %7D)%0A%0A
     
@@ -1788,24 +1788,47 @@
 ((err) =%3E %7B%0A
+    logger.error(err)%0A%0A
     const me
@@ -2119,24 +2119,24 @@
 hen(() =%3E %7B%0A
-
       return
@@ -2160,10 +2160,364 @@
 %7D)%0A  %7D)%0A
+  .finally(() =%3E %7B%0A    // Remove the beacons%0A    return P.props(%7B%0A      removeBeaconFrom: db.child(%60beacons/$%7Bfrom%7D%60).set(null),%0A      removeBeaconLocationFrom: db.child(%60beaconLocations/$%7Bfrom%7D%60).set(null),%0A      removeBeaconTo: db.child(%60beacons/$%7Bto%7D%60).set(null),%0A      removeBeaconLocationTo: db.child(%60beaconLocations/$%7Bto%7D%60).set(null),%0A    %7D)%0A  %7D)%0A
 %7D%0A

Add geodata to connection