dofile( "data/scripts/lib/utilities.lua" )

local entity_id = GetUpdatedEntityID()
local pos_x, pos_y, current_rotation = EntityGetTransform( entity_id )
local projectile_component = EntityGetFirstComponent( entity_id, "ProjectileComponent" )
local velocity_component = EntityGetFirstComponent( entity_id, "VelocityComponent" )

local speed = 400
local shrapnel_count = 8

local shrapnel_entities = {}

SetRandomSeed(pos_x,pos_y)

for i = 1, shrapnel_count do
    local shrapnel = EntityLoad("mods/spellbound_bundle/files/entities/projectiles/shrapnel.xml", pos_x, pos_y)
    table.insert(shrapnel_entities, shrapnel)
end

local original_damage = tonumber(ComponentGetValue(projectile_component, "damage"))
local original_explosion_damage = 0
if(tonumber(ComponentGetValue(projectile_component, "on_death_explode")) == 1 or tonumber(ComponentGetValue(projectile_component, "on_lifetime_out_explode")) == 1)then
    original_explosion_damage = tonumber(ComponentObjectGetValue(projectile_component, "config_explosion", "damage"))
end

local shrapnel_damage = (original_damage+original_explosion_damage) * 0.4

local shooter = ComponentGetValue(projectile_component, "mWhoShot")

if(shrapnel_damage < 0.025)then
    shrapnel_damage = 0.025
end

shoot_projectile_from_projectile( entity_id, "mods/spellbound_bundle/files/entities/misc/shrapnel_explosion.xml", pos_x, pos_y, 0, 0 )

for k,v in ipairs(shrapnel_entities)do


    edit_component( v, "VelocityComponent", function(comp,vars)

        local dir_x = math.random() + math.random(-1, 0)
        local dir_y = math.random() + math.random(-1, 0)

        local force_x = dir_x * speed
        local force_y = dir_y * speed
        
        ComponentSetValueVector2( comp, "mVelocity", force_x, force_y )

    end)	

    edit_component( v, "ProjectileComponent", function(comp,vars)
        vars.mWhoShot       = shooter
        vars.mShooterHerdId = 0
        vars.damage = tostring(shrapnel_damage)
    end)  
    
end