class RoomScene extends egret.Sprite {

  private startLabel: egret.TextField
  private players: Array<any>

  public constructor() {
    super();
    this.init()
  }

  // 初始化(给开始按钮绑定点击事件)
  private init() {
    console.log('RoomScene.init')
    this.initBg()
    this.initStartLabel()

    this.addChild(this.startLabel);
    // put display object to this scene
  }

  public update(data) {
    const payload = data.payload
    if (payload.seat == 0) {
      this.startLabel.text = '开始'
      this.startLabel.touchEnabled = true
      this.startLabel.addEventListener(egret.TouchEvent.TOUCH_TAP, this.startHandler, this)
    } else {
      this.startLabel.text = '等待房主点击开始'
      this.startLabel.touchEnabled = false
    }
  }

  private initBg() {
    var shape: egret.Shape = new egret.Shape();
    shape.graphics.beginFill(0x343E5F);
    shape.graphics.drawRect(0, 0, 2000, 2000);
    shape.graphics.endFill();
    this.addChild(shape);
    var bg: egret.Bitmap = new egret.Bitmap()
    bg.texture = RES.getRes("logo_jpg")
    bg.scaleX = bg.scaleY = 2
    bg.x = 1334 / 2 - 280
    bg.y = 100
    this.addChild(bg)
  }
  private initStartLabel() {
    this.startLabel = new egret.TextField()
    this.startLabel.textColor = 0xF0D66D
    this.startLabel.text = "请稍等..."
    this.startLabel.width = 300
    this.startLabel.anchorOffsetX = 150
    this.startLabel.x = 1334 / 2
    this.startLabel.textAlign = egret.HorizontalAlign.CENTER;
    this.startLabel.y = 1136 / 2
  }

  private startHandler() {
    console.log('starthandler')
    platform.sendSocketMessage({
      data: JSON.stringify({
        type: 'start',
        rid: 'default_room',
        cid: Store.getState().cid,
        payload: {
          avatar_url: Store.getState().userInfo.avatarUrl,
          nick_name: Store.getState().userInfo.nickName
        }
      }),
      success: res => {
        this.startLabel.text = '3'
        const timer = setInterval(() => {
          if(this.startLabel.text == '1') {
            return this.startLabel.text = 'Go!'
          }
          if(this.startLabel.text == 'Go!') {
            clearInterval(timer)
            SceneManager.getInstance().changeScene('gameScene')
            return
          }
          this.startLabel.text = `${Number(this.startLabel.text) - 1}`
        }, 1000)
      },
      fail: res => {
        this.startLabel.text = '启动失败'
      }
    })
  }

  public release() {
    // 移除事件
    this.startLabel.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.startHandler, this)
  }
}