
var MongoClient = require('mongodb').MongoClient;
var cachedDb = null;

// Get state, Query state, remote: true
module.exports = function(state, action, callback) {
  var uri = action.input['Mongo URI']

  var dbaction = {
    type: 'MongoDB initialize',
    input: {
      'Mongo URI': uri
    }
  }

  state.dispatch(dbaction, function(err, db){
    if (action.input['Property name']) {
      getOne(db, action.input['Property name'], callback)
    } else {
      getMany(db, action, callback)
    }
  })
}

function getMany(db, action, callback) {
  var properties = action.input['Properties']
  var records = []
  next(0)
  function next(i) {
    var property = properties[i]
    if (!property) return callback(null, records)
    var name = property['Property name']
    getOne(db, name, (err, doc) => {
      records.push(doc)
      next(i + 1)
    })
  }
}

function getOne(db, property, callback) {
  // Users/123/Profile
  var fragments = property.split('/')
  var collection = fragments.shift()
  var select = {}
  select[fields.join('.')] = 1
  db.collection(collection).findOne({ _id: id }, select).then(doc => {
    var i = 0
    while (i < fields.length) {
      var field = fields[i]
      if (doc) doc = doc[field]
      i++
    }
    callback(null, doc)
  })
}

function connectToDatabase(uri) {
  if (cachedDb && cachedDb.serverConfig.isConnected()) {
    console.log('=> using cached database instance');
    return Promise.resolve(cachedDb);
  }

  return MongoClient.connect(uri).then(db => { cachedDb = db; return cachedDb; });
}
