import { Node, Slider, _decorator, instantiate } from 'cc'

import DialogBase from '../../script/engine/uicomponent/DialogBase'
import MusicPrefab from '../../script/engine/uicomponent/MusicPrefab'
import SoundPrefab from '../../script/engine/uicomponent/SoundPrefab'
import EventManager from '../../script/engine/utils/EventManager'
import PrefabLoader from '../../script/engine/utils/PrefabLoader'
import { GameConfig } from '../../script/game/config/GameConfig'

const { ccclass, property } = _decorator

@ccclass('FishSetting')
export default class FishSetting extends DialogBase {
  @property({ type: Slider })
  private musicSlider: Slider | null = null

  @property({ type: Slider })
  private soundSlider: Slider | null = null

  onLoadMe() {
    EventManager.instance.addSliderEvent(this.node, this.musicSlider.node, 'onMusicSlider', 0)
    EventManager.instance.addSliderEvent(this.node, this.soundSlider.node, 'onSoundSlider', 0)
    this.refresh()
  }

  // 音乐
  private onMusicSlider(slider: Slider, customEventData) {
    const percent: number = Number(slider.progress.toFixed(3))
    MusicPrefab.changeVolumn(percent)
    this.refresh()
  }

  // 声音
  private onSoundSlider(slider: Slider, customEventData) {
    const percent: number = Number(slider.progress.toFixed(3))
    SoundPrefab.changeVolumn(percent)
    this.refresh()
  }

  // 刷新音乐和声音
  private refresh() {
    this.musicSlider.progress = MusicPrefab.musicVolumn
    this.soundSlider.progress = SoundPrefab.soundVolumn
  }

  public static show(parentNode: Node = null) {
    PrefabLoader.loadPrefab(`${GameConfig.GameName}/game/dialog/FishSetting`, (loadedResource) => {
      if (!parentNode) parentNode = DialogBase.GetRootCanvas()

      const node: Node = instantiate(loadedResource)
      parentNode.addChild(node)
      node.setPosition(0, 0)
    })
  }
}
