const express = require('express');
const os = require('os');
const readline = require('readline');
const { build } = require('./buildCocos');

const networkInfo = os.networkInterfaces();

let host = '';
for (const infos of Object.values(networkInfo)) {
  for (const info of infos) {
    if (info.family == 'IPv4') {
      if (info.address.split('.')[0] != "127") {
        host = info.address;
      }
    }
  }
}

var app = express();

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

app.get('/', function (req, res) {
  res.send('Hello World');
})

let port = '';
var server = app.listen(8081, function () {

  port = server.address().port

  console.log("测试服务已启动：%s:%s", host, port)
  console.log("如果已经build可访问如下地址");
  console.log("http://%s:%s/dist/play/index.html", host, port)
  console.log("http://%s:%s/dist/play/index.html", "localhost", port)

})

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', async (str) => {
  if (str.trim() == 'build') {
    await build();
    console.log("测试服务已启动：%s:%s", host, port)
    console.log('输入 build 构建。')
  } else {
    console.log("测试服务已启动：%s:%s", host, port)
    console.log('输入 build 构建。')
  }
})
