/* eslint-disable import/no-dynamic-require */
import 'server/bootstrap/setup'

import repl from 'repl'
import path from 'path'
import fs from 'mz/fs'
import { promirepl } from 'promirepl'
import clearRequire from 'clear-require'

const MODEL_DIRECTORY = path.join(__dirname, '../src/server/models')
const JOB_DIRECTORY = path.join(__dirname, '../src/server/jobs')

;(async () => {
  const r = repl.start()

  async function getModels() {
    const models = await fs.readdir(MODEL_DIRECTORY)
    return models.reduce((models, model) => {
      if (model.match(/\.test\.js$/)) {
        return models
      }

      models[model.replace(/\.js$/, '')] = require(path.join(MODEL_DIRECTORY, model)).default
      return models
    }, {})
  }

  async function getJobs() {
    const jobs = await fs.readdir(JOB_DIRECTORY)
    return jobs.reduce((jobs, job) => {
      if (job.match(/\.test\.js$/)) {
        return jobs
      }

      jobs[job.replace(/\.js$/, 'Job')] = require(path.join(JOB_DIRECTORY, job)).default
      return jobs
    }, {})
  }

  const reload = async (log = true) => {
    if (log) console.log('Reloading...') // eslint-disable-line no-console
    clearRequire.match(new RegExp(MODEL_DIRECTORY))
    const models = await getModels()
    const jobs = await getJobs()
    Object.assign(r.context, models, jobs, { reload })
    if (log) console.log('Reloaded!') // eslint-disable-line no-console
  }

  await reload(false)
  promirepl(r)
})().catch(err => setTimeout(() => { throw err }))

@@ -559,32 +559,57 @@
 h(/%5C.test%5C.js$/)
+ %7C%7C !model.match(/%5C.js$/)
 ) %7B%0A        retu
@@ -1093,18 +1093,8 @@
 nc (
-log = true
 ) =%3E
@@ -1095,33 +1095,24 @@
  () =%3E %7B%0A   
- if (log)
  console.log
@@ -1113,19 +1113,17 @@
 le.log('
-Rel
+L
 oading..
@@ -1344,17 +1344,8 @@
 %0A   
- if (log)
  con
@@ -1358,11 +1358,9 @@
 og('
-Rel
+L
 oade
@@ -1422,13 +1422,8 @@
 oad(
-false
 )%0A  

fix repl