import { TestMongo } from './testMongo'
import { MockApiRegistry } from './apiRegistry'
import { MockTracker } from './mockTracker'
import { MockMongoMirror } from './mockMongoMirror'


const possiblyRunTimerFuncInFiber = timer =>
  (func, timeout) => {
    const wasInFiber = require('fibers').current
    return timer(
      () => {
        if (wasInFiber) {
          func.future()().resolve((err) => {
            if (err) {
              throw err
            }
          })
        } else {
          func()
        }
      },
      timeout,
    )
  }

export default (meteorProperties = { isServer: true, isClient: false, isCordova: false }) =>
  () => {
    const {
      Meteor,
      SimpleSchema,
      Random,
      Accounts,
    } = global
    Accounts.users = new TestMongo.Collection('users')
    Meteor.users = Accounts.users
    Accounts._options = {}
    if (meteorProperties.isServer) {
      Accounts._loginHandlers = []
      Accounts._validateLoginHook.callbacks = {}
      Accounts._onLogoutHook.callbacks = {}
      delete Accounts._onCreateUserHook
    }
    const result = {
      Meteor: {
        ...meteorProperties,
        wrapAsync: Meteor.wrapAsync,
        defer: func => Meteor.setTimeout(func, 0),
        setTimeout: possiblyRunTimerFuncInFiber(setTimeout),
        clearTimeout,
        setInterval: possiblyRunTimerFuncInFiber(setInterval),
        clearInterval,
      },
      Mongo: TestMongo,
      Users: Accounts.users,
      SimpleSchema,
      apiRegistry: new MockApiRegistry(),
      Accounts,
      Random,
    }
    if (meteorProperties.isClient) {
      result.Tracker = new MockTracker()
      result.mongoMirror = new MockMongoMirror()
    }
    return result
  }

@@ -1603,24 +1603,48 @@
     
-result.
+Object.assign(result, %7B%0A        
 Tracker
- =
+:
  new
@@ -1661,22 +1661,18 @@
 er()
+,
 %0A      
-result.
+  
 mong
@@ -1678,18 +1678,17 @@
 goMirror
- =
+:
  new Moc
@@ -1701,16 +1701,43 @@
 Mirror()
+,%0A        api: %7B%7D,%0A      %7D)
 %0A    %7D%0A 

Add api into mock meteorCoreModuleFactory