'use strict';
const config = require('../config');
if (!process.env.NODE_ENV) {
    process.env.NODE_ENV = JSON.parse(config.dev.env.NODE_ENV);
}
const opn = require('opn');
const path = require('path');
const express = require('express');
const webpack = require('webpack');
const webpackConfig = require('./webpack.dev.conf');

const port = process.env.PORT || config.dev.port;
const autoOpenBrowser = config.dev.autoOpenBrowser;

const app = express();
const proxyMiddleWare=require('http-proxy-middleware');
const proxy_path='http://192.168.2.164:3000';
const proxy_option ={target:proxy_path,changeOrigin:true};
const compiler = webpack(webpackConfig);

const devMiddleware = require('webpack-dev-middleware')(compiler, {
    publicPath: webpackConfig.output.publicPath,
    quiet: true
});

const hotMiddleware = require('webpack-hot-middleware')(compiler, {
    log: false,
    heartbeat: 2000
});

app.use(hotMiddleware);
app.use(require('connect-history-api-fallback')());
app.use(devMiddleware);

const staticPath = path.posix.join(config.dev.assetsPublicPath, config.dev.assetsSubDirectory);

app.use(staticPath, express.static('./'));

app.use('/',proxyMiddleWare(proxy_option));

var _resolve;
var _reject;
var readyPromise = new Promise((resolve, reject) => {
    _resolve = resolve;
    _reject = reject;
});

var server;
var portfinder = require('portfinder');
portfinder.basePort = port;

console.log('> Starting dev server...');
devMiddleware.waitUntilValid(() => {
    portfinder.getPort((err, port) => {
        if (err) {
            _reject(err)
        }
        process.env.PORT = port;
        // var uri = 'http://localhost:' + port;
        const uri=`http://localhost:${port}?patientNo=1600&doctorNo=YS001&deptId=D01&recordId=44&hospitalId=A001`;
        console.log('> Listening at ' + uri + '\n');
        // when env is testing, don't need open it
        if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
            opn(uri)
        }
        server = app.listen(port);
        _resolve();
    })
});

module.exports = {
    ready: readyPromise,
    close: () => {
        server.close()
    }
};
