:NAME distract


:PARAM s_ping_effect@				ping

:VAR float32						unused


-- ------------------- globals ------------------- 

k_cell_center= e_value("e_cell_location", "_cell_center")

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

function param_initialize(p)
end

function var_initialize(v)
end


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


function attach(object)
	local ws= world_state_get()
	local ps= ws.plate_state_get("distract")
	if (ps) then
		ws.place_plate(ps.plate)
	end
end

function finish(object)
	local ws= world_state_get()
	local ps= ws.plate_state_get("distract")
	if (ps) then
		ps.tween_animation_play("end")
	end
	
	object_delete(object)
end


function update(object)

	local touch_interface= touch_get()
	
	if (touch_interface and touch_interface.touch_started()) then
		local touch_index= touch_interface.touch_start_index()
		local touch= touch_interface.touch[touch_index]
		local touch_object= touch.touch_handler_object
		if (touch_object) then
			local placement= touch_object.placement
			if (placement and placement.name == "distract_matte") then
				local ws= world_state_get()
				local player= ws.primary_player_get()
				if (player) then
					local target= player.target_get()
					if (target) then
						local screen_pos= touch.screen_position
						local camera= ws.camera[0]
						local world_pos= camera.screen_to_world(screen_pos.x, screen_pos.y, 0)
						local location= ws.nearest_traversable_location(world_pos.x, world_pos.y)
						local arena= location.arena_handle
						
						if (arena) then
							local cell= location.cell
							world_pos = arena.cell_location_get(cell.x, cell.y, k_cell_center)

							-- phew! make the sound!							
							target.make_sound_at_point(world_pos.x, world_pos.y, 1.0, true)
							
							-- and now make a ping
							if (param.ping) then
								local distance_map= object.distance_map_get()
								if (distance_map) then
									distance_map.compute_at_point(world_pos.x, world_pos.y);
									distance_map.distance_map.ping(param.ping);
								end
							end
							
							local sound= object.sound_get()
							if (sound) then
								sound.play_sound("activate", false)
							end
							
							-- having made the sound we can end ourselves
							finish(object)

						else
							-- didn't hit the arena properly
							local sound= object.sound_get()
							if (sound) then
								sound.play_sound("fail", false)
							end

							-- place a touch error
							local spawn= object.spawn_get("touch_error")
							if (spawn) then
								local te= spawn.spawn()
								if (te) then
									ws.object_move_to_plate(te, touch_object.plate);
									te.position_set(screen_pos.x, screen_pos.y)
								end
							end
						end
					end
				end
			end
		end
	end

end

component_register(attach, update, nil, nil)
