const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const chokidar = require('chokidar')
const express = require('express')
const Mock = require('mockjs')
const router = express.Router()

const mockDir = path.join(process.cwd(), 'mock')

function responseFake(url, type, respond) {
  return {
    url: new RegExp(`${url}`),
    type: type || 'get',
    response (req, res) {
      console.log('request invoke:' + req.path)
      res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond))
    }
  }
}

function register (router) {
  require('./proxy').register(router)

  router.use(express.json())
  router.use(express.urlencoded({
    extended: true
  }))

  const routeDir = path.join(__dirname, 'routes')
  if (fs.existsSync(routeDir)) {
    const routes = []
    fs.readdirSync(routeDir).forEach(file => {
      const mocks = require(`./routes/${file}`)
      if (Array.isArray(mocks) && mocks.length) {
        routes.push(...mocks)
      }
    })
    routes.forEach(route => {
      const { type, url, response } = responseFake(route.url, route.type, route.response)
      router[type](url, response)
    })
  } else {
    console.log('no mock routes')
  }
}

function unregister () {
  router.stack = []

  // clear routes cache
  Object.keys(require.cache).forEach(i => {
    if (i.includes(mockDir)) {
      delete require.cache[require.resolve(i)]
    }
  })
}

module.exports = app => {
  app.use(process.env.VUE_APP_BASE_API, router)
  register(router)

  // watch files, hot reload mock server
  chokidar.watch(mockDir, {
    ignored: /mock-server/,
    ignoreInitial: true
  }).on('all', (event, path) => {
    if (event === 'change' || event === 'add') {
      try {
        unregister()
        register(router)
        console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
      } catch (error) {
        console.log(chalk.redBright(error))
      }
    }
  })
}
