const express = require('express');
const os = require('os');
const readline = require('readline');
const Base64 = require('js-base64');
const CryptoJS = require("crypto-js");
const http = require("http");
const { build, buildAndroid, buildIos } = 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();

// Access-Control-Allow-Origin: *

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

app.get('/', function (req, res) {
  res.header("Access-Control-Allow-Origin", "*");
  res.send('Hello World');
});

app.get('/getSign', function (req, res) {
  res.header("Access-Control-Allow-Origin", "*");

  const gameId = req.query.gameId;
  const openId = req.query.openId;

  const secretKey = "060d81c7abaf24c8ce2afc5a725c152062676d35"; //替换为控制台上的 游戏 Key

  const nonce = Math.floor(Math.random() * 1000000000);
  const timestamp = Math.floor(new Date().getTime() / 1000);

  const str = `game_id=${gameId}&nonce=${nonce}&open_id=${openId}&timestamp=${timestamp}`;
  const sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(str, secretKey));

  res.send(JSON.stringify({ nonce, timestamp, sign }));
});

// app.get('/jump', function (req, res) {
//   res.header("Access-Control-Allow-Origin", "*");

//   const gameId = req.query.gameId;
//   const openId = req.query.openId;

//   http.get({
//     hostname: 'staging-teach.ireadabc.com',
//     port: 80,
//     path: `/api/oxford/game/v1/config?gameid=${gameId}&openid=${openId}`,
//     agent: false  // 仅为这个请求创建新代理
//   }, (getres) => {
//     getres.setEncoding('utf8');
//     let rawData = '';
//     getres.on('data', (chunk) => { rawData += chunk; });
//     getres.on('end', () => {
//       const secretKey = "060d81c7abaf24c8ce2afc5a725c152062676d35"; //替换为控制台上的 游戏 Key
//       const data = JSON.parse(rawData);

//       const str = `game_id=${gameId}&nonce=${data.nonce}&open_id=${openId}&timestamp=${data.timestamp}`;
//       const sign = CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(str, secretKey));
//       console.log('sign = ' + sign);
//       res.send(rawData)
//     });
//   });
// });

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)
  console.log('-----------------');
  console.log("    输入 build 构建安卓脚本");
  console.log("    输入 build ios 构建IOS脚本");
  console.log('-----------------');

})

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})
rl.on('line', async (str) => {
  if (str.trim() == 'build') {
    await buildAndroid();
  } else if (str.trim() == 'build ios') {
    await buildIos();
  }
  console.log("服务器：%s:%s", host, port)
})
