import Phaser from 'phaser'
import DialogManager from '../manager/dialogmanager'

class Dialog extends Phaser.GameObjects.Sprite {
  constructor (scene, x, y) {
    super(
      scene, x, y,
      'dialog',
      0
    )
    this.setOrigin(0, 1)
    this.alpha = 0
  }

  init (scene) {
    // Text
    this.text = scene.add.text(
      this.x + 10,
      this.y - this.height + 10,
      '',
      {
        fontSize: '16px',
        fontFamily: 'Arial',
        color: '#eee'
      }
    ).setOrigin(0, 0)

    this.goalText = ''
    this.typeWritterTimer = null

    // Next Button
    this.nextBtn = scene.add.sprite(
      this.x + this.width - 50,
      this.y - 50,
      'next'
    ).setOrigin(0.5, 0.5)
    this.nextBtn.alpha = 0
    this.nextBtn.setInteractive()

    this.nextBtn.on('pointerdown', (e) => {
      this.nextBtn.setScale(0.8)
    })
    this.nextBtn.on('pointerover', (e) => {
      this.nextBtn.setFrame(1)
    })
    this.nextBtn.on('pointerout', (e) => {
      this.nextBtn.setScale(1.0)
      this.nextBtn.setFrame(0)
    })
    this.nextBtn.on('pointerup', (e) => {
      DialogManager.nextStep()
      this.nextBtn.setScale(1.0)
    })
  }

  typewriteText (text) {
    this.goalText = text
    this.text.text = ''
    let i = 0
    this.typeWritterTimer = this.scene.time.addEvent({
      callback: () => {
        this.text.text += this.goalText[i]
        ++i
      },
      repeat: this.goalText.length - 1,
      delay: 30
    })
  }

  setText (text, showNext) {
    if (this.typeWritterTimer !== null) this.typeWritterTimer.remove()

    if (!text) {
      this.text.setText('')
      this.alpha = 0
    } else {
      this.typewriteText(text)
      this.alpha = 1
    }

    if (showNext) {
      this.nextBtn.alpha = 1
    } else {
      this.nextBtn.alpha = 0
    }
  }
}

export default Dialog
