-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- Game updates - abandon
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------


CREATE OR REPLACE FUNCTION sys.process_planet_abandon_updates( c_tick BIGINT )
		RETURNS VOID
		STRICT VOLATILE
		SECURITY INVOKER
	AS $$
DECLARE
	p_id	INT;
BEGIN
	-- Lock all records
	PERFORM p.name_id
		FROM sys.updates su
			INNER JOIN verse.planets_updates vu
				USING ( update_id , updtype_id , updtgt_id )
			INNER JOIN verse.planets p
				USING ( name_id )
			INNER JOIN emp.planets ep
				ON ep.planet_id = p.name_id 
			INNER JOIN emp.empires e
				ON e.name_id = ep.empire_id
			INNER JOIN emp.abandon a
				ON a.planet_id = p.name_id
		WHERE su.update_last = c_tick AND su.update_state = 'PROCESSING'
		FOR UPDATE;

	-- Handle planets where time has run out
	FOR p_id IN SELECT p.name_id
					FROM sys.updates su
						INNER JOIN verse.planets_updates vu
							USING ( update_id , updtype_id , updtgt_id )
						INNER JOIN verse.planets p
							USING ( name_id )
							INNER JOIN emp.abandon a ON a.planet_id = p.name_id
					WHERE su.update_last = c_tick AND su.update_state = 'PROCESSING'
						AND a.time_left = 1
	LOOP
		PERFORM emp.leave_planet( p_id );
	END LOOP;
	
	-- Update all abandon records
	UPDATE emp.abandon a SET time_left = a.time_left - 1
		FROM sys.updates su
			INNER JOIN verse.planets_updates vu
				USING ( update_id , updtype_id , updtgt_id )
		WHERE su.update_last = c_tick AND su.update_state = 'PROCESSING'
			AND a.planet_id = vu.name_id;
END;
$$ LANGUAGE plpgsql;

SELECT sys.register_update_type( 'Planets' , 'PlanetAbandon' ,
		'Planets are being abandoned.' ,
		'process_planet_abandon_updates'
	);