
var MongoClient = require('mongodb').MongoClient;
var objectid = require('mongodb').ObjectID;

var cachedDb = null;

module.exports = function(state, action, callback) {
  var dbaction = {
    type: 'MongoDB initialize',
    input: {}
  }
  state.dispatch(dbaction, function(err, db) {
    if (action.input['Property name']) {
      updateOne(db, action.input['Property name'], action.input['Property value'], callback)
    } else {
      updateMany(db, action, callback)
    }
  })

  function updateMany(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']
      var value = property['Property value']
      updateOne(db, name, value, function(err, doc) {
        records.push(doc)
        next(i + 1)
      })
    }
  }

  function updateOne(db, property, value, callback) {
    // Users/123/Profile
    var [ collection, id, ...fields ] = property.split('/')
    var query = objectid.isValid(id)
      ? { _id: id }
      : {}
    var updates = {
      [fields.join('.')]: value
    }
    if (!query._id) {
      db.collection(collection).insert(updates).then(function(doc) {
        db.collection(collection).findOne({ _id: doc._id }).catch(function(err) {
          console.log('find err', err)
        }).then(function(doc) {
          callback(null, doc)
        })
      })
      return
    }
    try {
      db.collection(collection).update(query, { $set: updates }, { upsert: true }).catch(function(err) {
        console.log('update err', err)
      }).then(function(doc) {
        console.log('DOC1')
        console.log(doc)
        db.collection(collection).findOne({ _id: doc._id }).catch(function(err) {
          console.log('find err', err)
        }).then(function(doc) {
          callback(null, doc)
        })
      })
    } catch (e) {
      console.log('ERR')
      console.log(e)
    }
  }
}

