import Phaser from 'phaser'
import GamblingManager from '../manager/gamblingmanager'

class DiceGroup extends Phaser.GameObjects.Group {
  constructor (scene) {
    super(scene)

    this.dices = []
    this.createDice(scene, true)
    this.createDice(scene, false)
  }

  createDice (scene, isPlayerSide) {
    // const i = this.dices.length
    const basex = 150
    const basey = 220

    const dice = new DiceEntity(
      scene,
      isPlayerSide ? basex : this.scene.game.canvas.width - basex - 64, // basex + i * 70,
      basey,
      isPlayerSide
    )
    this.add(dice, true)
    this.dices.push(dice)
  }

  reset () {
    for (const i in this.dices) {
      this.dices[i].reset()
    }
  }

  animate () {
    this.dices[0].animate()
    this.dices[1].animate()
  }

  show () {
    this.setAlpha(1)
  }

  hide () {
    this.setAlpha(0)
  }

  update () {
    for (const i in this.dices) {
      this.dices[i].update()
    }
  }
}

class DiceEntity extends Phaser.GameObjects.Sprite {
  constructor (scene, x, y, isPlayerSide) {
    super(
      scene, x, y,
      'dice', 0
    )
    this.setOrigin(0, 0)
    this.isPlayerSide = isPlayerSide
    this.isShaking = false
    this.startx = x
    this.starty = y
  }

  getFrameNum (num) {
    if (this.isPlayerSide) {
      return num - 1
    } else {
      return 5 + num
    }
  }

  reset () {
    this.setFrame(this.getFrameNum(1))
  }

  animate () {
    this.isShaking = true
    this.scene.time.delayedCall(500, () => {
      const diceVal = (
        this.isPlayerSide ? GamblingManager.myDice : GamblingManager.otherDice
      )
      this.setFrame(this.getFrameNum(diceVal))
    })
    this.scene.time.delayedCall(1000, () => {
      this.isShaking = false

      if (this.isPlayerSide) {
        GamblingManager.endGame()
      }
    })
  }

  update () {
    if (this.isShaking) {
      this.x = this.startx + Phaser.Math.RND.integerInRange(-10, 10)
      this.y = this.starty + Phaser.Math.RND.integerInRange(-10, 10)
    } else {
      this.x = this.startx
      this.y = this.starty
    }
  }
}

export default DiceGroup
