import {asyncDelay} from './util.js'


export class NetworkHelper {

  _eventListeners: any = {};

  client: any;
  playerId: any;
  currentPlayer: any;
  room: any;
  roomType: any;
  maxPlayers: any;
  startFrameSyncCallback: any;
  isStartFrameSync: any;
  userInfo: any;
  tempRoomPlayer: any;


  ctor() { 

  }

  on(eventName, func) {
    this._eventListeners[eventName] = func;
  }

  async init(roomType: string, maxPlayers: number) {
    // 人数只支持2～10个 ～～

    this.userInfo = await this.initUserInfo();
    console.log('this.userInfo: ', this.userInfo);

    this.maxPlayers = maxPlayers;
    this.roomType = roomType;
    await this.initEngine();

    this.initTempRoomPlayer();

    // await this.initRoom();

    return this.userInfo.id;
  }

  initTempRoomPlayer() {
    const playerInfo = this.initPlayerInfo();
    this.userInfo.playerInfo = playerInfo;
    this.tempRoomPlayer = [ this.userInfo ];
  }

  initUserInfo() {

    return new Promise((resolve, reject) => {
      if ( cc.find('middleLayer') &&  cc.find('middleLayer').getComponent('middleLayer')?.getUserInfo ) {
      
        cc.find('middleLayer').getComponent('middleLayer').getUserInfo().then((res)=> {
          resolve(res);
        })
      } else {
        setTimeout(() => {
          const userInfo = {
            nick_name: '拼读达人',
            avatar_url: '1',
            id: 'id_' + new Date().getTime()
          };
          resolve(userInfo);
        }, 100);
      
      }
    })
  }

  async initEngine() {


    const client = new window.GOBE.Client({
      clientId: '860627598634404416',// 客户端ID
      clientSecret: '83B0DCE6407CBEFAD5786BAC07A73EBAF8E688E2CABA779724FC000C0714C8E7',// 客户端密钥
      appId: '105878157',// 应用的ID
      openId: this.userInfo.id,// 玩家ID
    });
    this.client = client;


    return new Promise((resolve, reject) => {
      client.init().then(() => {
        // 初始化成功
        console.log(' 华为 对战联机引擎 初始化成功')
        console.log('``client: ', client);
        this.playerId = client.playerId;
        resolve('');
  
      }).catch((e) => {
        // 初始化失败
        console.log(' 华为 对战联机引擎 初始化失败')
        reject();
  
      });
    })


  }

  async initRoom() {

    console.log('初始化 房间')
    const playerInfo = this.initPlayerInfo();

    return new Promise((resolve, reject) => {


      this.client.matchRoom({
        matchParams: {
          matchRule: 'match_rule_' + this.maxPlayers,
        //  matchRule2: 'xxxx',
        },
        roomType: this.roomType,
        customRoomProperties: 'customRoomProperties_xxx',
        // roomStatus: ROOM_STATE_IDLE,
        maxPlayers: this.maxPlayers,
        
      },{customPlayerStatus: 0, customPlayerProperties: JSON.stringify(playerInfo)}).then((room) => {
        // 房间匹配成功
        console.log('房间匹配成功: ', room);

        this.currentPlayer = room.player;
        this.room = room;
        this.addRoomListener(room);
        this.initRoomPlayerInfo();

        resolve('');

      }).catch((e) => {
        // 房间匹配失败
        console.log(' in initRoom error:', e)

        reject();
      });
    })



  }

  initRoomPlayerInfo() {

    const players = this.room.players;
    players.forEach(p => {
      this.setCustomPlayerProperties(p);
    })
  }

  initPlayerInfo() {

    // 初始化玩家基础数据

    const nick_name = this.userInfo?.nick_name || '拼读达人';
    const avatar_url = this.userInfo?.avatar_url || '1';
    const avatar = this.getAvatar(avatar_url);
    const playerInfo = {
      playerId: this.playerId,
      matchParams: {
        level: 1,
      },

      name: nick_name,
      avatar,
      customPlayerStatus: 0,
    };

    if (this.userInfo) {
      this.userInfo.playerId = this.playerId;
    }

    return playerInfo;
  }

  getAvatar(avatar_url) {
    let avatar = 'http://staging-teach.cdn.ireadabc.com/0751c28419a0e8ffb1f0e84435b081ce.png';
    if (cc.find('middleLayer') && cc.find('middleLayer').getComponent('middleLayer')?.getHeadUrl) {
      avatar = cc.find('middleLayer').getComponent('middleLayer').getHeadUrl(avatar_url);
    } 
    return avatar;
  }

  addRoomListener(room) {

    // 添加房间玩家进入监听
    room.onJoin((playerInfo) => {
      //有玩家加入房间，做相关游戏逻辑处理
      console.log('  onJoin :', playerInfo);

      this.playerJoin(playerInfo);
    });


    // 添加帧同步开始通知回调
    room.onStartFrameSync(() => {
      // 接收帧同步开始通知，处理游戏逻辑
      console.log("接收帧同步 开始")
      if (this.startFrameSyncCallback) {
        this.startFrameSyncCallback.call();
      }
      this.isStartFrameSync = true;
      
    });

    // 添加帧同步停止通知回调
    room.onStopFrameSync(() => {
      // 接收帧同步停止通知，处理游戏逻辑
      console.log("接收帧同步 停止")
    });

    // 添加接收帧同步信息回调
    room.onRecvFrame((msg) => {
      // 处理帧数据msg
      
      if (this._eventListeners['frameEvent']) {
        this._eventListeners['frameEvent'](msg);
      }
    });


    // 离开房间事件
    room.onLeave((playerInfo) => {
      // 有玩家离开房间，做相关游戏逻辑处理
      console.log('  onLeave :', playerInfo);
      this.updateRoom();

      if (this._eventListeners['playerLeave']) {
        this._eventListeners['playerLeave'](playerInfo);
      }
    });

  }

  playerJoin(data) {
    // 有玩家加入
    this.updateRoom(() => {

      const playerData = this.getRoomPlayerById(data.playerId);
      if (!playerData) {
        return;
      } 
  
      this.setCustomPlayerProperties(playerData);
      this._eventListeners['playerJoin'](playerData);
    });

  }

  setCustomPlayerProperties(playerData) {
    // 兼容老模板
    if ( !playerData.playerInfo) {
      console.log('string : ',  playerData.customPlayerProperties);
      playerData.playerInfo = JSON.parse(playerData.customPlayerProperties);
    }
  }


  leaveRoom() {

    // 离开房间
    this.client.leaveRoom().then((client) => {
      // 退出房间成功
      console.log(' 退出房间成功 ')
      console.log(' client: ', client);
    }).catch((e) => {
      // 退出房间失败
      console.log(' 退出房间失败 ')

    });
  }

  updateRoom(cb = null) {

    console.log('in updateRoom');
    // 更新一下房间数据
    this.room.update().then(() => {
      // 更新玩家房间信息成功，做相关的游戏处理逻辑

      console.log('update this.room: ', this.room);
      // this.checkCanStart();
      cb && cb();
    }).catch(() => {
      // 更新玩家房间信息失败
    });
  }

  getOnlinePlayers() {
    return this.tempRoomPlayer;

    // 获取房间中 还在线上的玩家列表

    const onlinePlayers = [];
    const players = this.room.config.players;
    for (let i=0; i<players.length; i++) {
      if (players[i].status == 1) {

        onlinePlayers.push(players[i]);
      }
    }
    return onlinePlayers
  }

  checkIsOwner() {
    return true;
    // 检查是不是房主 之前房主随时有掉线的可能
    const onlinePlayers = this.getOnlinePlayers();
    const firstPlayer = onlinePlayers[0];

    return firstPlayer.playerId == this.playerId;
  }
  
  getRoomPlayerById(id) {
    return this.tempRoomPlayer[0]

    // 获取房间中特定id的玩家
    const players = this.room.config.players;
    const player = players.find(p => {
      return p.playerId == id;
    })
    return player;
  }


  startFrameSync(cb=null) {
    cb();
    return;
    console.log('开启帧同步 ..');
    if (this.isStartFrameSync) {
      console.log('开启帧同步 .. 1');
      return;
    }

    if (this.startFrameSyncCallback) {
      return;
    }

    // 开启帧同步
    if (cb) {
      this.startFrameSyncCallback = cb;
    }
    this.room.startFrameSync();

  }

  stopGame() {
    console.log('停止帧同步 ..');
    // 向联机对战后端发送停止帧同步请求
    this.room.stopFrameSync();
  }

  sendFrame(data: any) {
    const frameInfo = [{data: JSON.stringify(data)}];
    this._eventListeners['frameEvent']({frameInfo});
    return;
    // 发送帧数据
    this.room.sendFrame(JSON.stringify(data), err => {
      if (err.code != 0) {
        console.log("err", err)
      }
    });
  }
}