import type { DOStage } from "../models/DOStage"
import { EVENT_TYPES, EventManager } from "../models/EventManager"
import { StorageManager } from "../models/StorageManager"
import { UIManager } from "../models/UIManager"
import { Utility_ConvertSecondToString, Utility_EaseOut, Utility_EaseOut_2 } from "../utils/utility"

const { regClass, property } = Laya

@regClass()
export class GamePause extends Laya.Script {
  declare owner: Laya.Box

  @property(Laya.Label)
  public label_time: Laya.Label

  @property(Laya.Label)
  public label_diffucuty: Laya.Label

  @property(Laya.Box)
  public btn_continue: Laya.Box

  @property(Laya.Box)
  public btn_restart: Laya.Box

  private mask: Laya.Image
  private center: Laya.Box

  onAwake(): void {
    EventManager.getInstance().DispatchEvent(EVENT_TYPES.NOT_UPDATE_PAUSE, true)

    this.mask = this.owner.getChildByName("Image") as Laya.Image
    this.mask.alpha = 0
    Laya.Tween.to(this.mask, { alpha: 0.6 }, 400, Utility_EaseOut)

    this.center = this.owner.getChildByName("center") as Laya.Box
    this.center.scaleX = 0.8
    this.center.scaleY = 0.8
    Laya.Tween.to(this.center, { scaleX: 1, scaleY: 1 }, 400, Utility_EaseOut)
    this.center.alpha = 0
    Laya.Tween.to(this.center, { alpha: 1 }, 400, Utility_EaseOut)
  }

  onDestroy(): void {
    EventManager.getInstance().DispatchEvent(EVENT_TYPES.NOT_UPDATE_PAUSE, false)
  }

  destroyUI(): void {
    Laya.Tween.to(this.mask, { alpha: 0 }, 400, Utility_EaseOut_2)
    Laya.Tween.to(this.center, { scaleX: 0.8, scaleY: 0.8 }, 400, Utility_EaseOut_2)
    Laya.Tween.to(this.center, { alpha: 0 }, 400, Utility_EaseOut_2, Laya.Handler.create(this, () => {
      this.owner.destroy()
    }))
  }

  public onSetStageInfo(doStage: DOStage): void {
    this.label_time.text = Utility_ConvertSecondToString(doStage.get_duration())
    this.label_diffucuty.text = doStage.get_difficulty()

    this.mask.on(Laya.Event.CLICK, this, () => {
      this.destroyUI()
    })

    this.btn_continue.on(Laya.Event.CLICK, this, () => {
      this.destroyUI()
    })

    this.btn_restart.on(Laya.Event.CLICK, this, () => {
      const stageID = doStage.get_stageID()
      const type = doStage.get_stageType()
      const difficulty = doStage.get_difficulty()
      StorageManager.getInstance().newStage(stageID, type, difficulty, difficulty)
      UIManager.getInstance().loadStageUI(stageID)
      this.destroyUI()
    })
  }
}
