import { Hall } from "../../prefab/hall/Hall";
import { RewardLayer } from "../../prefab/layer/RewardLayer";
import { TipsLayer } from "../../prefab/layer/TipsLayer";
import { LinkGameConfirmLayer } from "../../prefab/play/LinkGameConfirmLayer";
import UserM, { GoodInfo } from "../api/UserM";
import WsM from "../api/WsM";
import { WS, WsResponse } from "../net/WS";
import Utils from "../utils/Utils";
import EV, { EV_TYPE } from "./EV";
import ItemsM from "./ItemsM";
import { Tips } from "./Tips";

export class RewardGoods {
  changeList: GoodInfo[];
  goodList: GoodInfo[];
}

export class BindGameUserInfo {
  userId: string;
  userName: string;
  wallet: string;
}
export class BindGameConfirmInfo {
  gameId: number;
  userList: BindGameUserInfo[];
}
export default class PushMsgM {
  private static _ins: PushMsgM = null;
  public static get ins(): PushMsgM {
    return (PushMsgM._ins ??= new PushMsgM());
  }

  init() {
    WS.ins.on(10001, this.onRechargeSuccess, this);
    WS.ins.on(10002, this.onBindGameConfirm, this);
    WS.ins.on(10003, this.onRefreshUserData, this);
    WS.ins.on(10004, this.onRewardGoods, this);

    WS.ins.on(10005, this.OnJoinFamilySuccess, this);
    WS.ins.on(10006, this.OnFamilyKickedMe, this);
    WS.ins.on(401, this.OnUserTokenError, this);
  }

  onBindGameConfirm(msg: WsResponse) {
    let data = msg.data as BindGameConfirmInfo;
    if (!data) {
      return;
    }
    if (!data.userList || data.userList.length == 0) {
      TipsLayer.showConfirm("", "This code is not valid");
      return;
    }
    LinkGameConfirmLayer.show(data);
  }

  async OnJoinFamilySuccess(msg: WsResponse) {
    await UserM.ins.refreshInfo();
    await TipsLayer.showConfirm(
      "",
      Utils.setI18nLabel("Family.JoinFamilySuccess")
    );
    EV.ins.emit(EV_TYPE.FAMILY_STATUS_UPDATE);

    Hall.ins.switchPage(Hall.PageFamily);
  }

  async OnFamilyKickedMe(msg: WsResponse) {
    let result = await TipsLayer.showConfirm(
      "",
      Utils.setI18nLabel("Family.KickedMe")
    );

    await UserM.ins.refreshInfo();
    EV.ins.emit(EV_TYPE.FAMILY_STATUS_UPDATE);
  }

  OnUserTokenError(msg: WsResponse) {
    console.warn("OnUserTokenError", msg);
    window.location.reload();
  }

  onRefreshUserData(msg: WsResponse) {
    console.warn("onRefreshUserData", msg);
    UserM.ins.refreshData();
  }
  onRechargeSuccess(msg: WsResponse) {
    console.warn("onRechargeSuccess", msg);
    console.warn("changeList", msg.data.changeList);
    ItemsM.ins.itemChange(msg.data.changeList, msg.data.goodList);
  }
  onRewardGoods(msg: WsResponse) {
    console.warn("onRewardGoods", msg);
    let data = msg.data as RewardGoods;
    // UserM.ins.refreshGoods(data.goodList);
    // RewardLayer.show(data.changeList);

    ItemsM.ins.itemChange(data.changeList, data.goodList);
  }
}
