:NAME required_loot

:GLOBAL float32 unused

:PARAM float32 pickup_distance

:VAR boolean have_ever_updated_before


-- ------------------- constants ------------------- 

local vectorlib = require "scripts/vector_math"

k_ui_time_mode= e_value("e_time_mode", "_time_mode_ui")


-- ------------------- initialization ------------------- 

function global_initialize(g)
end

function param_initialize(p)
	p.pickup_distance= 0.8
end

function var_initialize(v)
	v.have_ever_updated_before= false
end

-- ------------------- component ------------------- 

function attach(object)

end

function update(object)
	local w= world_get()
	local ws= world_state_get()
	
	if (not var.have_ever_updated_before) then  -- CB: hacky, but it works
		local game_hud= world_state_get().global_script("game_hud")
		
		if (game_hud) then
			game_hud.required_loot_counter = game_hud.required_loot_counter + 1
		end
		var.have_ever_updated_before = true
	end

	local player= ws.primary_player_get()
	local gear_manager= ws.global_script("gear_manager")
	if (gear_manager and gear_manager.player_proxy) then
		player= gear_manager.player_proxy
	end

	if (player) then
		local object_point= object.world_position_get()
		local player_point= player.world_position_get()
		
		if (vectorlib.distance2d(object_point, player_point) < param.pickup_distance) then
			local game_hud= world_state_get().global_script("game_hud")
			if (game_hud) then
				game_hud.required_loot_counter = game_hud.required_loot_counter - 1
			end
				
			local sound= object.sound_get()
			if (sound) then
				local aquired_sound= sound.get_sound_by_name("aquired")
				if (aquired_sound) then
					aquired_sound.play(k_ui_time_mode)
				end
			end
			
			local missing_spawner= object.spawn_get("required_loot_missing")
			if (missing_spawner) then
				local missing= missing_spawner.spawn()
				if (missing) then
					-- give him my scale and skew
					local scale= object.transform.scale
					local shear= object.transform.shear
					missing.scale_set(scale.x, scale.y)
					missing.shear_set(shear.x, shear.y)
				end
			end
			object.delete_all_children()
			object_delete(object)
		end
	end
end

component_register(attach, update, nil, nil)
