local DL = require("design.DesignerLibrary")
local healthObject, son, player
local INIT = 1
local TARGET = 2
local HOME = 3
local EXPLODE = 4
local END = 5
local state = HOME
local initialLocation
local speed = 12
local currentPercentage = 0
local percentageGain = 0
local rotationAmount = 0
local yOffset = 0
function OnScriptLoaded(level, go, ...)
  son = game.AI.FindSon()
  player = game.Player.FindPlayer()
  initialLocation = son:GetWorldJointPosition(son:GetJointIndex("JOLeftIndexA1"))
  healthObject = game.FX.Spawn("healthStoneFX", level)
  healthObject:SetWorldPosition(initialLocation)
  local dist = (player:GetWorldJointPosition(player:GetJointIndex("JOBack1")) - initialLocation):Length()
  if dist <= 0 then
    dist = 0.1
  end
  percentageGain = speed / dist
  local time = dist / speed * 0.5
  local yVelocity = 9.8 * time * time
  yOffset = yVelocity * time * 2
end
function OnUpdate(level, go)
  if state == HOME then
    local newPos = initialLocation + (player:GetWorldJointPosition(player:GetJointIndex("JOBack1")) - initialLocation) * currentPercentage
    local dt = level:GetUnitTime()
    currentPercentage = currentPercentage + percentageGain * dt
    newPos.y = newPos.y + yOffset * math.sin(math.rad(180 * currentPercentage))
    healthObject:SetWorldPosition(newPos)
    healthObject:SetWorldOrientation(rotationAmount, 0, 0)
    rotationAmount = rotationAmount + 720 * level:GetUnitTime()
    if 1 <= currentPercentage then
      state = EXPLODE
      game.FX.Spawn("runeActivateHealth_LODGRP", nil, {
        GameObject = player,
        Joint = "JOBack1",
        AutoDelete = true
      })
      if healthObject ~= nil then
        healthObject:Destroy()
      end
      if player:MeterGetValue("Health") < player:MeterGetMax("Health") and 0 < player:MeterGetValue("Health") then
        local healthRegen = 30
        local difficulty = player:AttributeGetValue("Difficulty")
        if difficulty ~= nil and difficulty == 4 then
          healthRegen = 20
        end
        local targetValue = math.min(player:MeterGetValue("Health") + healthRegen * SonArmorPerkModifier(), player:MeterGetMax("Health"))
        player:MeterSetValue("Health", targetValue)
      end
      local rumbleParams = {EffectName = "FFB_LARGE", Duration = 0.35}
      game.FX.SubmitEffect(rumbleParams)
      local kratosEmitter = player:FindSingleSoundEmitterByName("SNDKratos")
      kratosEmitter:Start("SND_LOOT_Shard_Green_Pickup")
    end
  elseif state == EXPLODE then
    state = END
    go:Destroy()
  end
end
function SonArmorPerkModifier()
  local son = game.AI.FindSon()
  if son == nil then
    return 1
  end
  if son:PickupIsAcquired("SonArmorDefense02") or son:PickupIsAcquired("SonArmorDefense03") or son:PickupIsAcquired("SonArmorBonus01") or son:PickupIsAcquired("SonArmorBonus02") or son:PickupIsAcquired("SonArmorBonus04") then
    return 1.35
  end
  return 1
end
