local this = class("cellFreeWorkProductionPet", G_UIModuleBase)
local _petTpl = L_GameTpl:getPetTpl()
local PetGifIconPath = "UI/Icon/PetPixelIcon/tex_icon_pet_%s_%d.png"
local MaxPetGifFrame = 8

function this.bind()
  return {img_pet = nil, active_img_designated = false}
end

function this:open()
  self.onRefreshPetHandler = handler(self, self.onRefreshPet)
  AzurWorld.petMgr:RegisterEvent(C_EPetEvent.refreshPet, self.onRefreshPetHandler)
end

function this:close()
  AzurWorld.petMgr:UnregisterEvent(C_EPetEvent.refreshPet, self.onRefreshPetHandler)
  L_TimerManager:clearTimer(self)
end

function this:refreshData(petGuid)
  self.UIData = {}
  self.UIData.petGuid = petGuid
  local csPetData = L_PetStore:getCsPetData(self.UIData.petGuid)
  self.UIData.petId = L_PetStore:getPetConfigId(csPetData)
  self.UIData.curPetGifFrame = 1
  self.UIData.isDesignated = L_PetStore:getPetIsDesignated(csPetData)
  local petId = self.UIData.petId
  local petTpl = _petTpl:getTplById(petId)
  local petItem = L_PetStore:getPetItem(petGuid)
  local isSpecial = petItem:isSpecialPet()
  local initFrameIcon = _petTpl:getPetPixelIcon(petTpl, isSpecial)
  self.UIData.petGifPixelIconIdStr = string.match(initFrameIcon, "%a*%d+")
  self:refreshInnerData()
end

function this:refreshInnerData()
end

function this:refreshUI()
  self.bind.active_img_designated = self.UIData.isDesignated
  self:playPetGif()
  L_TimerManager:newOrResetTimer(self, "petGif", function()
    self:playPetGif()
  end, 0.1, -1)
end

function this:playPetGif()
  local singlePetIconPath = string.format(PetGifIconPath, self.UIData.petGifPixelIconIdStr, self.UIData.curPetGifFrame)
  self.bind.img_pet = singlePetIconPath
  self.UIData.curPetGifFrame = self.UIData.curPetGifFrame % MaxPetGifFrame + 1
end

function this:onRefreshPet()
  self:refreshInnerData()
  self:refreshUI()
end

return this
