local this = class("state_singlePhotoAction", require(L_R.world.core .. "stateMachine.baseState"))

function this:ctor(...)
  self.super.ctor(self, ...)
end

function this:onEnter(args)
  this.super.onEnter(self, args)
  local state = self.animatorComponent:getState(args.animName)
  self.args = args
  if state then
    self.animatorComponent.animator.applyRootMotion = false
    self:doAction(state, args.isLoop, args.callback)
    self:setRevertCondition()
  else
    self:complete()
  end
end

function this:onLeave(state)
  if state and state == L_Const.stateStep.replace then
  else
    self.animatorComponent.animator.applyRootMotion = true
    if self.state then
      local speed = self.animatorComponent.animator.speed
      local dt = (0.99 - math.min(self.state.normalizedTime, 1)) * self.state.length * speed
      C_MediaPackUtility.AnimatorTimelineEvaluate(self.entity:getCsEntity(), dt)
    end
    self.animatorComponent:setSpeed(1)
    C_MediaPackUtility.ChangeEffectSpeed(self.entity:getCsEntity(), 1, true)
    self.state = nil
    self.animatorComponent:crossFade(L_Const.anim.idle)
  end
  for _, v in pairs(self.timers) do
    Timer.remove(v)
  end
  self.timers = {}
  this.super.onLeave(self)
end

function this:destroy()
  this.super.destroy(self)
  for _, v in pairs(self.timers) do
    Timer.remove(v)
  end
  self.timers = {}
end

function this:invokeCallBack()
  if self.callback then
    self.callback()
    self.callback = nil
  end
end

function this:doAction(state, isLoop, callback)
  self.callback = callback
  self.animatorComponent:play(state.stateName, self.args.normalize)
  if self.args.setPause ~= nil then
    self.animatorComponent:setSpeed(self.args.setPause and 0 or 1)
  end
  self.state = state
  self.timers.action = L_GameTimer.repeated(0, function()
    if not state.isRunning or state.normalizedTime >= 0.999 then
      if isLoop then
        self.animatorComponent:play(state.stateName)
      else
        self.complete()
      end
    end
  end, self, self.entity:getGameObject())
  self:invokeCallBack()
end

return this
