local this = class("timelineAssetHandle")

function this:ctor()
  self._clipMap = {}
  self.loadTimelineAssetFinishHandle = nil
  self._curTimelineName = nil
  self._curTimelineAssetName = nil
  self.control = nil
end

function this:dispose()
  for i, v in pairs(self._clipMap) do
    for _i, _v in pairs(v) do
      v[_i] = nil
    end
    self._clipMap[i] = nil
  end
  self._clipMap = nil
  self.loadTimelineAssetFinishHandle = nil
  self._curTimelineName = nil
  self._curTimelineAssetName = nil
  self.control = nil
end

function this:loadTimelineAssetFinish(timelineName, timelineAssetName, timelineAsset)
  self._curTimelineName = timelineName
  self._curTimelineAssetName = timelineAssetName
  if self.loadTimelineAssetFinishHandle then
    self.loadTimelineAssetFinishHandle(timelineName, timelineAssetName, timelineAsset)
  end
end

function this:loadTimelineAsset(timelineName, timelineAssetName, customCallback)
  local clipPath = self:getFilePath(timelineName, timelineAssetName)
  self._clipMap[timelineName] = self._clipMap[timelineName] or {}
  local timelineAsset = self._clipMap[timelineName][timelineAssetName]
  if timelineAsset then
    if customCallback then
      customCallback(timelineName, timelineAssetName, timelineAsset)
    else
      self:loadTimelineAssetFinish(timelineName, timelineAssetName, timelineAsset)
    end
    return
  end
  C_LuaUtility.LoadTimelineAsset(clipPath, function(_timelineAsset)
    if self.control == nil then
      return
    end
    if self._clipMap == nil then
      return
    end
    local TimelineUtility = CS.Lens.Gameplay.Tools.TimelineExtensions.TimelineUtility
    TimelineUtility.InstantiateSubAssets(_timelineAsset, {
      typeof(CS.UnityEngine.Timeline.AvatarAnimationTrack)
    })
    self._clipMap[timelineName][timelineAssetName] = _timelineAsset
    if customCallback then
      customCallback(timelineName, timelineAssetName, _timelineAsset)
    else
      self:loadTimelineAssetFinish(timelineName, timelineAssetName, _timelineAsset)
    end
  end)
end

function this:getFilePath(timelineName, timelineAssetName)
  local path = timelineName .. "/timeline_" .. timelineAssetName .. ".playable"
  return path
end

return this
