import {
  Component,
  Game,
  Node,
  Prefab,
  Sprite,
  Tween,
  Vec3,
  _decorator,
  director,
  game,
  instantiate,
} from 'cc'

import FishMover from '../../../fish/script/FishMover'
import FishWiki from '../../../fish/script/FishWiki'
import TextureMgr from '../../engine/uicomponent/TextureMgr'
import { Logger } from '../../engine/utils/Logger'
import RandomUtil from '../../engine/utils/RandomUtil'
import { FishPathConfig } from '../config/FishPathConfig'
import { FishPathInfo } from '../config/FishPathInfo'
import WsManager from '../manager/WsManager'
import GameMusicHelper from '../utils/GameMusicHelper'
import CommonTips from '../../engine/uicomponent/CommonTips'

const { ccclass, property } = _decorator

@ccclass('FishGameScene')
export default class FishGameScene extends Component {
  @property(Sprite)
  private bg: Sprite | null = null

  @property({ type: [Prefab] })
  private fishPrefabList: Array<Prefab> | null = []

  private showNode: Node | null = null

  onLoad() {
    this.onLoadMe()
  }

  onDestroy() {
    this.onDestroyMe()
  }

  onLoadMe() {
    WsManager.instance.init()
    GameMusicHelper.playBg()
    WsManager.instance.on(400, this.showMsg, this)
    // FishPathConfig.init()
    // this.initBg()
    // this.testPathPlay()
    game.on(Game.EVENT_HIDE, this.onHide, this)
    game.on(Game.EVENT_SHOW, this.onAppShow, this)
  }

  private initBg() {
    const textureMgr: TextureMgr = this.bg.getComponent(TextureMgr)
    this.bg.spriteFrame =
      textureMgr.Spriteset[RandomUtil.nextInt(0, textureMgr.Spriteset.length - 1)]
  }

  private initShowNode() {
    if (this.showNode) {
      this.showNode.destroy()
      this.showNode = null
    }
    const fishType: number = 29
    if (fishType < 1 || fishType > 29) return

    this.showNode = instantiate(this.fishPrefabList[fishType - 1])
    this.showNode.getComponent(FishMover).speed = 2
    this.showNode.getComponent(FishMover).node.setScale(new Vec3(2, 2, 1))
    this.node.addChild(this.showNode)
  }

  private testPathPlay() {
    this.initShowNode()
    const pathInfo: FishPathInfo = FishPathConfig.getPathInfo(3)
    Logger.log('testPathPlay=pathInfo=', pathInfo)
    const params = pathInfo.path
    const param0 = params[0]
    Logger.log('testPathPlay=11=', param0)
    this.showNode.setPosition(new Vec3(param0.x, param0.y, 0))
    this.showNode.getComponent(FishMover).bezierPList = params
    this.showNode.getComponent(FishMover).startMove()
  }

  private onClickWiki() {
    FishWiki.show()
  }

  private showMsg(res: any) {
    Logger.log('showMsg=res=', res)
    CommonTips.showMsg(res.msg)
  }

  onDestroyMe() {
    this.unscheduleAllCallbacks()
    // this.node.stopAllActions();
    Tween.stopAllByTarget(this.node)
  }

  onHide() {
    director.pause()
  }

  onAppShow() {
    director.resume()
  }
}
