const axios = require('axios').default;
const parseArgs = require('minimist');
const ClientNet = require('./clientnet');

function getTickCount() {
  return Math.floor((new Date()).getTime() / 1);
}

function getArgv(name, def = null) {
  const argv = parseArgs(process.argv.slice(2), opts = {
    string: [name]
  });
  return argv[name] ? argv[name] : def;
}

function httpGet(url, params) {
  return new Promise((resolve) => {
    const ret = {
      err: null,
      response: null,
    };
    axios({
      method: 'get',
      url: url,
      timeout: 1000 * 5,
      params: params,
      responseType: 'text'
    }).then((response) => {
      ret.response = response.data;
      resolve(ret);
    }).catch((error) => {
      ret.err = error;
      resolve(ret);
    });
  });
}

async function sleep(timeout) {
  return new Promise(function (resolve, reject) {
    setTimeout(function () {
      resolve();
    }, timeout);
  });
}

class TestCase {

  constructor(url) {
    this.relationUrl = getArgv('h');
    console.log(this.relationUrl);
    this.openId = getArgv('u');
    this.protoDir = getArgv('d');
    this.loginData = null;
    this.userData = null;
    console.log(this.protoDir);
    this.relationWs = new ClientNet(
      this.relationUrl,
      this.protoDir + 'proto/cs_proto.proto',
      this.protoDir + 'proto/cs_msgid.proto'
    );
  }

  async init() {
    await this.step1();
    await this.step2();
    await this.step3();
    while (true) {
      await sleep(1000 * 3);
    }
  }

  async step1() {
    const startTick = getTickCount();
    const {err, response} = await httpGet(
      'https://login-test.kingsome.cn/webapp/index.php',
      {
        'c': 'Login',
        'a': 'auth',
        'gameid': 2006,
        'channel': 6513,
        'openid': this.openId
      });
    this.loginData = response;
    const endTick = getTickCount();
    //console.log('login auth@Login', endTick - startTick,  String(err), response);
  }

  async step2() {
    const startTick = getTickCount();
    const {err, response} = await httpGet(
      'https://game2006api-test.kingsome.cn/webapp/index.php',
      {
        'c': 'User',
        'a': 'login',
        'account_id': this.loginData.account_id,
        'session_id': this.loginData.session_id,
      });
    this.userData = response;
    const endTick = getTickCount();
    console.log('login auth@User', endTick - startTick,  String(err), response);
  }

  async step3() {
    await this.relationWs.init();
    await this.relationWs.connect();
    this.relationWs.on('connect', () => {
      console.log('relation onConnect');
      this.relationWs.accountId = this.loginData['account_id'];
      this.relationWs.sessionId = this.loginData['session_id'];
      this.relationWs.sendMsg('CMLogin', {
        account_id: this.loginData['account_id'],
        session_id: this.loginData['session_id'],
        create_team_param: {
          map_id: 2003
        }
      });
    });
  }

}

module.exports = TestCase;
