local util = {}

function util.playEffect(effectPath, effectParent, scale, offset, dimension, pos)
  local pathSplit = string.split(effectPath, "/")
  local effectName = string.split(pathSplit[#pathSplit], ".")[1]
  local effect = effectParent.transform:Find(effectName)
  if L_CommonUtil.isValid(effect) then
    C_GameObject.DestroyImmediate(effect.gameObject)
  end
  effect = L_ResPool:syncGameObject(effectPath)
  effect.name = effectName
  effect.transform:SetParent(effectParent.transform)
  local rectTrans = effect:GetComponent(typeof(C_RectTransform))
  if dimension then
    rectTrans.sizeDelta = dimension
  end
  if scale then
    rectTrans.localScale = scale
  else
    rectTrans.localScale = L_Vector3.one
  end
  if offset then
    rectTrans.anchoredPosition = offset
  else
    rectTrans.anchoredPosition = C_Vector2.zero
  end
  if pos then
    local temPos = rectTrans:InverseTransformPoint(pos)
    local localPosition = L_Vector3.new(temPos.x, temPos.y, 0)
    L_Vector3.setLocalPos(rectTrans, localPosition)
  end
  util.playAudio(effectName)
  return effect
end

function util.playAnimation(node, animationName, callback, owner)
  local animator = node.gameObject:GetComponent(typeof(C_CsAnimator))
  animator:Play(animationName, -1, 0)
  local length = L_EffectUtil.GetClipLength(animator, animationName)
  Timer.once(length, function()
    if callback then
      callback()
    end
  end, owner, node.gameObject)
end

function util.GetClipLength(animator, clipName)
  local clip = L_CommonUtil.getClip(animator, clipName)
  if clip then
    return clip.length
  end
  return 0
end

function util.playAudio(effectName)
  if effectName == "pre_circleButtonEffect" then
    L_AudioUtil.playSound("Play_SFX_System_HUD_Guide_Hint_Circle_Appear")
  elseif effectName == "pre_squareButtonEffect" then
    L_AudioUtil.playSound("Play_SFX_System_HUD_Guide_Hint_Square_Appear")
  end
end

function util.isElementVerticalVisible(uiElement, viewPortRect, contentRect)
  local uiElementRect = uiElement:GetComponent(typeof(C_RectTransform))
  local itemSize = uiElementRect.sizeDelta
  local itemPos = uiElementRect.anchoredPosition
  local viewPortRectSize = viewPortRect.rect.size
  local contentPos = contentRect.anchoredPosition
  if math.abs(contentPos.y) > math.abs(itemPos.y) then
    return false, math.abs(itemPos.y), true
  end
  if viewPortRectSize.y + math.abs(contentPos.y) > itemSize.y + math.abs(itemPos.y) then
    return true, math.abs(itemPos.y) - (viewPortRectSize.y - itemSize.y)
  end
  return false, math.abs(itemPos.y) - (viewPortRectSize.y - itemSize.y)
end

return util
