export class GameServer {

  userArr = [];
  resultArr = [];
  gameDuration = 20;
  userMax = 6;
  networkHelper;

  constructor() {
  }

  setNetworkHelper(nh) {
    this.networkHelper = nh;

    this.registerListener();

  }

  registerListener() {

		const c = window.courseware;
		if (!c) {
			return;
		}
		
    // // 收到1条结果
		// c.onEvent('send_result', (data, next) => {
		// 	this.resultArr.push(data);
		// 	next();
		// });

    // c.onEvent('send_good', (data, next) => {
		// 	this.sendEvent('get_good', data)
		// 	next();
		// });
  }

  // 添加一个用户
  addUser(data) {

    console.log('addUser ~~~~~~~ ');

    if (this.userArr.length >= this.userMax) {
      return false;
    }

    this.userArr.push(data);

    if (this.userArr.length >= this.userMax) {
      this.gameStart();
    }
    return true;
  }

  gameStart() {

    // this.sendEvent('game_start', {});

    console.log(' in gameStart closeRoom')


    this.networkHelper.closeRoom().then(() => {

      console.log(' in closeRoom cb')
      this.networkHelper.sendFrame({ key: 'game_start', data: {} })

    });

  }

  gameTimeStart() {
    const delayTime = 3;
    this._timeoutIds.push(setTimeout(() => {
      this.gameEnd();
    }, (this.gameDuration + delayTime) * 1000));
  }

  gameEnd() {

    const c = window.courseware;
    if (!c) {
      return;
    }

    console.log('getAnswer  start ..')
    c.getAnswer({ templateName: 'OP10_online' }, (res) => {
      console.log('getAnswer res: ', res);

      if (res) {
        this.sendEvent('game_end', res);
      }
    })

    // this.sendEvent('game_end', this.resultArr);
  }






  sendEvent(evtName, data) {
    const c = window.courseware;
    if (!c) {
      return;
    }

    c.sendEvent(evtName, data);
  }

  _timeoutIds = [];
  _intervalIds = [];
  // 生命周期
  onDestroy() {
    this._timeoutIds.forEach(id => {
      clearTimeout(id);
    });
    this._intervalIds.forEach(id => {
      clearInterval(id);
    });
  }

}