dofile( "data/scripts/lib/utilities.lua" )
--dofile( "mods/spellbound_bundle/files/spellbound/scripts/cloneentity.lua" )
function load_entities_to_entity( files, entity_id )
    local blacklisted_members = {
        "mPersistentValues",
        "mLuaManager",
        "m_collision_angles",
        "m_cached_image_animation",
    }
  -- print(files)
    local file_table = string.gmatch(files, '([^,]+)')
    local x, y, r = EntityGetTransform(entity_id)
    for file in file_table do
        EntityLoadToEntity(file, entity_id)
        

    --[[    local modifier = EntityLoad(file, x, y)
        if(modifier ~= nil)then
            local modifier_components = EntityGetAllComponents( modifier )
            for k,component in pairs(modifier_components) do
                local component_members = ComponentGetMembers(component)
                if(ComponentGetTypeName(component) ~= "ProjectileComponent")then
                    local moved_component = EntityAddComponent(entity_id, ComponentGetTypeName(component))
                   -- print("Component "..ComponentGetTypeName(moved_component).." has been moved to hit entity")
                    for membername,member in pairs(component_members) do
                        local allowed = true
                        for _,v in pairs(blacklisted_members) do
                            if v == membername then
                                allowed = false
                            end
                        end
                        if(allowed)then
                            ComponentSetValue2(moved_component, membername, ComponentGetValue2(component, membername))
                        end
                    end
                end
            end
        end
        EntityKill(modifier)]]
    end
end


function damage_received( damage, message, entity_thats_responsible, is_fatal  )
    if(is_fatal)then
       -- print("Fatal Damage")
        local entity_id = GetUpdatedEntityID()
        local x, y, r = EntityGetTransform(entity_id)


		SetRandomSeed(x + GameGetFrameNum(), y + GameGetFrameNum())

        if(EntityHasTag( entity_id, "mortal" ))then


            local player = entity_thats_responsible

            local action_id = nil
            local extra_entities = nil
            local material = nil
            local trail_material = nil
            local material_amount = nil
            local trail_material_amount = nil
            local game_effect_entities = nil
            
            local components = EntityGetComponent( entity_id, "VariableStorageComponent" )

            if( components ~= nil ) then
                for key,comp_id in pairs(components) do 
                    local var_name = ComponentGetValue( comp_id, "name" )
            
                    if( var_name == "action_id") then
                       -- print("found action ID")
                        action_id = ComponentGetValue2(comp_id, "value_string")
                    end
                    if( var_name == "extra_entities") then
                        extra_entities = ComponentGetValue2(comp_id, "value_string")
                    end     
                    if( var_name == "game_effect_entities")then
                        game_effect_entities = ComponentGetValue2(comp_id, "value_string")
                    end
                    if( var_name == "material") then
                        material = ComponentGetValue2(comp_id, "value_string")
                    end 
                    if( var_name == "material_amount") then
                        material_amount = tonumber(ComponentGetValue2(comp_id, "value_string"))
                    end        
                    if( var_name == "trail_material") then
                        trail_material = ComponentGetValue2(comp_id, "value_string")
                    end        
                    if( var_name == "trail_material_amount") then
                        trail_material_amount = tonumber(ComponentGetValue2(comp_id, "value_string"))
                    end                                                                                  
                end
            end  
            
            if(action_id == nil)then

                print("Missing Action ID")
                return
            end
           -- print("action_id: "..action_id)
            local filename = GlobalsGetValue("ACTION_"..action_id, "")


          --  print("Filename: "..filename)
            if(filename == "")then
                print("Invalid Action ID")
                return
            end
           -- 	
            local count = 1
            
            if(filename ~= "" and count ~= 0)then
               -- local nearby_entities = EntityGetInRadiusWithTag( x, y, 200, "homing_target" )

              --  if(nearby_entities[1] ~= nil)then
                    for i=1, count do
                        
                        local ourProjectile = EntityLoad(filename, x, y - 5)


                        print("Projectile Loaded")
                        --clone_all_components( entity_id, ourClone, component)
                        if(extra_entities ~= nil)then
                            load_entities_to_entity( extra_entities, entity_id )
                        end
                        if(game_effect_entities ~= nil)then
                            load_entities_to_entity( game_effect_entities, entity_id )
                        end

                        GameShootProjectile( player, x, y - 5, Random(-100, 100), -500, ourProjectile )

                        local projectileComp = EntityGetFirstComponent(ourProjectile, "ProjectileComponent")

                        local ceremonial_damage = damage

                        ComponentObjectSetValue2(projectileComp, "config", "material", material)
                        ComponentObjectSetValue2(projectileComp, "config_explosion", "create_cell_material", material)
                        if(ComponentObjectGetValue2(projectileComp, "config_explosion", "create_cell_probability") < material_amount)then
                            ComponentObjectSetValue2(projectileComp, "config_explosion", "create_cell_probability", material_amount)
                        end
                        ComponentObjectSetValue2(projectileComp, "config", "material_amount", material_amount)
                        ComponentObjectSetValue2(projectileComp, "config", "trail_material", trail_material)
                        ComponentObjectSetValue2(projectileComp, "config", "trail_material_amount", trail_material_amount)

                        local trail_materials = string.gmatch(trail_material, '([^,]+)')

                        for our_material in trail_materials do

                            trail_material_amount_min = trail_material_amount + 1
                            trail_material_amount_max = trail_material_amount + 3
    
                            EntityAddComponent(ourProjectile, "ParticleEmitterComponent", {
                                airflow_force="0",
                                airflow_scale="1",
                                airflow_time="1",
                                area_circle_sector_degrees="360",
                                attractor_force="0",
                                b2_force="0",
                                collide_with_gas_and_fire="1",
                                collide_with_grid="1",
                                color="0",
                                cosmetic_force_create="1",
                                count_max=trail_material_amount_min,
                                count_min=trail_material_amount_max,
                                create_real_particles="0",
                                custom_style="NONE",
                                delay_frames="0",
                                direction_random_deg="0",
                                draw_as_long="0",
                                emission_chance="100",
                                emission_interval_max_frames="0",
                                emission_interval_min_frames="0",
                                emit_cosmetic_particles="0",
                                emit_real_particles="1",
                                emitted_material_name=our_material,
                                emitter_lifetime_frames="-1",
                                fade_based_on_lifetime="0",
                                fire_cells_dont_ignite_damagemodel="0",
                                friction="0",
                                image_animation_colors_file="",
                                image_animation_emission_probability="1",
                                image_animation_file="",
                                image_animation_loop="1",
                                image_animation_phase="0",
                                image_animation_raytrace_from_center="0",
                                image_animation_speed="1",
                                image_animation_use_entity_rotation="0",
                                is_emitting="1",
                                is_trail="1",
                                lifetime_max="10",
                                lifetime_min="5",
                                particle_single_width="1",
                                render_back="1",
                                render_on_grid="0",
                                set_magic_creation="0",
                                trail_gap="0",
                                use_material_inventory="0",
                                velocity_always_away_from_center="0",
                                x_pos_offset_max="2.23607",
                                x_pos_offset_min="-2.23607",
                                x_vel_max="0",
                                x_vel_min="0",
                                y_pos_offset_max="2.23607",
                                y_pos_offset_min="-2.23607",
                                y_vel_max="0",
                                y_vel_min="0",
                            })
                        end



                        edit_component( ourProjectile, "ProjectileComponent", function(comp,vars)
                            vars.mWhoShot       = entity_thats_responsible
                            vars.mShooterHerdId = 0
                            vars.penetrate_world = 1
                            vars.penetrate_world_velocity_coeff = 1.0
                            vars.damage = ceremonial_damage
                        end)                                
                        
                        edit_component( ourProjectile, "VelocityComponent", function(comp,vars)
                            ComponentSetValueVector2( comp, "mVelocity", Random(-300, 300), Random(-300, 300))
                        end)
                
                        EntityAddComponent( ourProjectile, "HomingComponent",
                        {
                            homing_targeting_coeff="300.0",
                            homing_velocity_multiplier="0.9",
                            detect_distance="200",
                        })
                   -- end
                end
            end
        end
    end
end
