--[[
BY
 _____   _____   __   _  
|  _  \ /  _  \ |  \ | | 
| | | | | | | | |   \| | 
| | | | | | | | | |\   | 
| |_| | | |_| | | | \  | 
|_____/ \_____/ |_|  \_| 

]]

local function DoEffects(pet)
    local x, y, z = pet.Transform:GetWorldPosition()
    GLOBAL.SpawnPrefab("shadow_despawn").Transform:SetPosition(x, y, z)
end

local function KillPet(pet)
    pet.components.health:Kill()
end

local function OnSpawnPet(inst, pet)
    if pet:HasTag("shadowminionskeleton") then
        pet:DoTaskInTime(0, DoEffects)

        if not (inst.components.health:IsDead() or inst:HasTag("playerghost")) then
            inst.components.sanity:AddSanityPenalty(pet, TUNING.SHADOWWAXWELL_SANITY_PENALTY[string.upper(pet.prefab)])
        elseif pet._killtaskdon == nil then
            pet._killtaskdon = pet:DoTaskInTime(math.random(), KillPet)
        end
    elseif inst._OnSpawnPetDon ~= nil then
        inst:_OnSpawnPetDon(pet)
    end
end

local function OnDespawnPet(inst, pet)
    if pet:HasTag("shadowminionskeleton") then
        DoEffects(pet)
        pet:Remove()
    elseif inst._OnDespawnPetDon ~= nil then
        inst:_OnDespawnPetDon(pet)
    end
end

local function OnDeath(inst)
    for k, v in pairs(inst.components.petleash_don:GetPets()) do
        if v:HasTag("shadowminionskeleton") and v._killtaskdon == nil then
            v._killtaskdon = v:DoTaskInTime(math.random(), KillPet)
        end
    end
	
	if inst.prefab == "waxwell" then --só para o maxwell
		for k, v in pairs(inst.components.petleash:GetPets()) do
			if v:HasTag("shadowminion") and v._killtask == nil then
				v._killtask = v:DoTaskInTime(math.random(), KillPet)
			end
		end
    end
end

local function donpetskeletonsset(inst)
    if inst.components.petleash_don ~= nil then
        inst._OnSpawnPetDon = inst.components.petleash_don.onspawnfn
        inst._OnDespawnPetDon = inst.components.petleash_don.ondespawnfn
        inst.components.petleash_don:SetMaxPets(inst.components.petleash_don:GetMaxPets() + 2)
    else
        inst:AddComponent("petleash_don")
        inst.components.petleash_don:SetMaxPets(2)
    end
    inst.components.petleash_don:SetOnSpawnFn(OnSpawnPet)
    inst.components.petleash_don:SetOnDespawnFn(OnDespawnPet)

    inst:ListenForEvent("death", OnDeath)
    inst:ListenForEvent("ms_becomeghost", OnDeath)
end


for k,prefabname in ipairs(GLOBAL.DST_CHARACTERLIST) do
	AddPrefabPostInit(prefabname, donpetskeletonsset)
end

for k,prefabname in ipairs(GLOBAL.MODCHARACTERLIST) do
	AddPrefabPostInit(prefabname, donpetskeletonsset)
end