local this = class("VoiceComponent", L_EcsConst.component)
local sConcat = string.concat

function this:ctor(...)
  this.super.ctor(self, ...)
  self.curPlay = nil
  self.curType = nil
  self.cvTimeCache = {}
end

function this:initialize(heroId)
  local heroTpl = L_GameTpl.getHeroTpl()
  local tpl = heroTpl:getTplById(heroId and heroId or self.parent:getId())
  local voice = heroTpl:getVoice(tpl)
  if not voice or voice == "" then
    self.voiceInvalid = true
  end
  self.voiceRes = sConcat("cv_", voice, "__")
end

function this:playVoice(cvType, index)
  if self.voiceInvalid then
    return
  end
  if L_CommonUtil.isValid(self.curPlay) then
    local curStatus = self.curPlay.EventIsEnd
    if curStatus == true then
      self:stopCurVoice()
    end
  end
  if self.curType == cvType then
    return
  end
  local cdRange = L_Const.cvCD[cvType]
  if cdRange then
    local lastPlayTime = self.cvTimeCache[cvType] or 0
    local cdTime = math.random(cdRange[1], cdRange[2])
    if cdTime > C_Time.time - lastPlayTime then
      return
    end
  end
  local curPriority = -1
  local newPriority = L_Const.cvPriority[cvType] or 0
  if self.curType and L_Const.cvPriority[self.curType] then
    curPriority = L_Const.cvPriority[self.curType]
  end
  if newPriority <= curPriority then
    return
  end
  self:stopCurVoice()
  local voiceEventName = sConcat(self.voiceRes, cvType)
  self.curPlay = C_AudioManager.Play(voiceEventName)
  if L_CommonUtil.isValid(self.curPlay) then
    self.curPlay:SetAutoRelease(false)
    self.curType = cvType
    self.cvTimeCache[cvType] = C_Time.time
  end
end

function this:onRemove()
  self:stopCurVoice()
end

function this:stopCurVoice()
  if L_CommonUtil.isValid(self.curPlay) then
    C_AudioManager.FreeSource(self.curPlay)
  end
  self.curPlay = nil
  self.curType = nil
end

return this
