-- 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.updates vu ON vu.update_id = su.id
			INNER JOIN verse.planets p ON p.name_id = vu.planet_id
			INNER JOIN emp.planets ep ON p.name_id = vu.planet_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.last_tick = c_tick AND su.status = 'PROCESSING'
			AND su.gu_type = 'PLANET_ABANDON'
		FOR UPDATE;

	-- Handle planets where time has run out
	FOR p_id IN SELECT p.name_id
					FROM sys.updates su
						INNER JOIN verse.updates vu ON vu.update_id = su.id
						INNER JOIN verse.planets p ON p.name_id = vu.planet_id
						INNER JOIN emp.abandon a ON a.planet_id = p.name_id
					WHERE su.last_tick = c_tick AND su.status = 'PROCESSING'
							AND su.gu_type = 'PLANET_ABANDON' 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.updates vu ON vu.update_id = su.id
		WHERE su.last_tick = c_tick AND su.status = 'PROCESSING'
			AND su.gu_type = 'PLANET_ABANDON' AND a.planet_id = vu.planet_id;
END;
$$ LANGUAGE plpgsql;