'use strict'
const path = require('path')
const express = require('express')
const httpProxy = require('http-proxy')
const webpack = require('webpack')
const webpackConfig = require('./webpack.dev')
const config = require('./config')
const LogPlugin = require('./log-plugin')
const open = require('open')

const app = express()
const apiProxy = httpProxy.createProxyServer()

const port = config.port
webpackConfig.entry.client = [
  'react-hot-loader/patch',
  'webpack-hot-middleware/client?reload=true',
  webpackConfig.entry.client
]

webpackConfig.plugins.push(new LogPlugin(port))

let compiler

try {
  compiler = webpack(webpackConfig)
} catch (err) {
  console.log(err.message)
  process.exit(1)
}

const devMiddleWare = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  quiet: false,
  hot: true,
  inline: true,
  headers: {
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*',
    'Access-Control-Allow-Headers': '*'
  }
})

app.use(devMiddleWare)
app.use(
  require('webpack-hot-middleware')(compiler, {
    log: console.log
  })
)

const mfs = devMiddleWare.fileSystem
const file = path.join(webpackConfig.output.path, 'index.html')

devMiddleWare.waitUntilValid()

app.get('*', (req, res) => {
  devMiddleWare.waitUntilValid(() => {
    const html = mfs.readFileSync(file)
    res.end(html)
  })
})

// Proxy api requests
app.use(process.env.BASE_API, function (req, res) {
  req.url = req.baseUrl
  apiProxy.web(req, res, {
    target: {
      port: 4000,
      host: 'localhost'
    }
  })
})

app.listen(port)

open(`http://localhost:${port}`)

@@ -178,16 +178,23 @@
 uire('./
+client/
 webpack.
@@ -310,30 +310,8 @@
 ')%0A%0A
-const app = express()%0A
 cons
@@ -357,19 +357,42 @@
 r()%0A
+const app = express()
 %0Aconst 
+%7B
 port
+%7D
  = c
@@ -400,13 +400,8 @@
 nfig
-.port
 %0Aweb
@@ -819,16 +819,66 @@
 icPath,%0A
+  // @Metnew: personally I prefer %60quite: %22true%22%60%0A
   quiet:
@@ -1455,16 +1455,28 @@
 requests
+ to BASE_API
 %0Aapp.use
@@ -1520,16 +1520,165 @@
  res) %7B%0A
+  /**%0A   * // req.baseUrl - The URL path on which a router instance was mounted.%0A   * %7B@link https://expressjs.com/ru/4x/api.html#req.baseUrl%7D%0A   */%0A
   req.ur
@@ -1692,16 +1692,26 @@
 .baseUrl
+ + req.url
 %0A  apiPr

fix import path for client webpack.base, some style fixes