var express = require('express')
var webpack = require('webpack')
var config = require('./webpack.devandroid.conf')
var proxyMiddleware = require('http-proxy-middleware')
var http = require('http')
// var httpProxy = require('http-proxy')

var app = express()
var compiler = webpack(config)
// var proxy = httpProxy.createProxyServer()

// Define HTTP proxies to your custom API backend
// https://github.com/chimurai/http-proxy-middleware
// var proxyTable = {
//   '/materials': {
//     target: 'http://192.168.50.202:8081'
//   },
//   '/images': {
//     // target: 'http://192.168.50.202:8081'
//     target: 'http://192.168.50.202:8081'
//   },
//   '/rs/user': {
//     target: 'http://192.168.50.202:8081'
//     // target: 'http://127.0.0.1:82'
//   },
//   '/SaleRest/rs': {
//     // target: 'http://127.0.0.1:8082'
//     target: 'http://127.0.0.1:8081/'
//   },
//   '/rs/db': {
//     // target: 'http://192.168.50.202:8081'
//     target: 'http://192.168.50.202:8081'
//   },
//   '/excel': {
//     // target: 'http://127.0.0.1:8082'
//     target: 'http://127.0.0.1:8081/'
//   },
//   '/rs': {
//     // target: 'http://127.0.0.1:8082'
//     target: 'http://127.0.0.1:8081/'
//   },
//   '/AndroidRest/rs': {
//     // target: 'http://127.0.0.1:8082'
//     target: 'http://127.0.0.1:8081'
//   },
//   '/rs/workflow': {
//     // target: 'http://127.0.0.1:8082'
//     target: 'http://127.0.0.1:8081/'
//   }
// }

var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: config.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  }
})

var hotMiddleware = require('webpack-hot-middleware')(compiler)
// force page reload when html-webpack-plugin template changes
compiler.plugin('compilation', function (compilation) {
  compilation.plugin('html-webpack-plugin-after-emit', function (data, cb) {
    hotMiddleware.publish({ action: 'reload' })
    cb()
  })
})

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(devMiddleware)

// enable hot-reload and state-preserving
// compilation error display
app.use(hotMiddleware)

// serve pure static assets
app.use('/static', express.static('./static'))

// module.exports = app.listen(8020, function (err) {
//   if (err) {
//     console.log(err)
//     return
//   }
//   console.log('Listening at http://localhost:8020')
// })

app.listen(8082, function (err) {
  if (err) {
    console.log(err)
    return
  }
  console.log('Listening at http://localhost:8082')
})

var proxyTable = {
  '/excel': {
    // target: 'http://127.0.0.1:8082'
    target: 'http://127.0.0.1:8081/'
  },
  // '/rs/user': {
  //   target: 'http://192.168.50.202:8081'
  //   // target: 'http://127.0.0.1:82'
  // }
}
http.get('http://127.0.0.1:8081/RestWork/rs/manager/config', (res) => {
  const { statusCode } = res

  let error
  if (statusCode !== 200) {
    error = new Error('请求失败。\n' +
      `状态码: ${statusCode}`)
  }
  if (error) {
    console.error(error.message)
    // 消耗响应数据以释放内存
    res.resume()
  }

  res.setEncoding('utf8')
  let rawData = ''
  res.on('data', (chunk) => { rawData += chunk })
  res.on('end', () => {
    try {
      let response = JSON.parse(rawData)
      Object.keys(response).forEach(function (key) {
        app.use(proxyMiddleware(key, response[key]))
      })
      // let key = '/rs/user'
      // Object.assign(proxyTable, {'/rs/user': response[key]})
      //console.log(proxyTable)
    } catch (e) {
      console.error(e.message)
    }
  })
}).on('error', (e) => {
  console.error(`错误: ${e.message}`)
})

// setTimeout(() => {
// // proxy api requests
//   Object.keys(proxyTable).forEach(function (context) {
//     var options = proxyTable[context]
//     if (typeof options === 'string') {
//       options = { target: options }
//     }
//     app.use(proxyMiddleware(context, options))
//   })
// }, 2000)
