// Import Modules
const INDEX = require('../../index.js')

// Import Packages
const _ = require('lodash')
const merge = require('merge')

// Define helper variables
const ws = INDEX.connection
const mongo = INDEX.mongo
const dispatcher = INDEX.dispatcher

/**
 * Function to watch for updates on all collections
 */
const watchUpdates = () => {
  for (var model in mongo.models) {
    ws.subscribe(`connapp.server.${model.toLowerCase()}.update`, function(data) {
      mongo.models[model]
      .findOne({_id: data._id}).exec()
      .then(res => {
        // deletes save so it won't conflict on merging
        delete res.save

        // merges with new data
        merge(res, data)

        // Makes sure this is treated as an update by the post save hook
        res.isNew = false

        // saves Updated item
        return res.save()
      })
      .then(res => {
        console.log(res)
      })
      .catch(err => console.log(err))
    })
  }
}

/**
 * Function to watch for inserts on all collections
 */
const watchInserts = () => {
  for (var model in mongo.models) {
    ws.subscribe(`connapp.server.${model.toLowerCase()}.insert`, function(data) {
      let doc = new mongo.models[model](data)

      // Make sure this is treated as new by the post-save hook
      doc.isNew = true

      doc.save()
        .then(res => {
          console.log(res)
        })
        .catch(err => console.log(err))
    })
  }
}

/**
 * Function to watch for inserts on all collections
 */
const watchSync = () => {
  for (var model in mongo.models) {
    const uri = `connapp.server.${model.toLowerCase()}.fetch`
    console.log(uri)
    ws.subscribe(uri, (args1, args2) => {
      console.log(args1, args2)
      console.log('Fetch was triggered')
      mongo.models[model]
        .find({}).exec()
        .then(data => {
          console.log('data found: ' + data)
          // If nothing is found, does nothing
          if (!data.length) return true
          console.log('is array? ' + Array.isArray(ids))
          // Loops through the found data and dispatch route accordingly
          data.forEach(item => {
            const _id = item._id.toString()

            if ( ids.indexOf(_id) == -1 ) {
              console.log('sent to insert '+ item)
              dispatcher.insertToApp(model, item)
            } else {
              console.log('sent to update '+ item)
              dispatcher.updateDocumentToApp(model, _id, item)
            }
          })
	      })
        .catch(err => console.log(err))
    })
  }
}

const watchersObj = {
  watchUpdates: watchUpdates,
  watchInserts: watchInserts,
  watchSync: watchSync
}

const runAllWatchers = () => _.mapValues(
  watchersObj,
  watcher => {
    var status = true

    try {
      watcher()
    } catch(e) {
      status = e
    }

    return status
  }
)

// Exports
module.exports = {
  list: watchersObj,
  watchersStatus: runAllWatchers()
}

@@ -1659,24 +1659,16 @@
 i, (args
-1, args2
 ) =%3E %7B%0A 
@@ -1692,16 +1692,17 @@
 args
-1, 
+.
 args
-2
+Dict
 )%0A  

Test again