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


CREATE OR REPLACE FUNCTION sys.process_planet_fleet_status_updates( c_tick BIGINT )
		RETURNS VOID
		STRICT VOLATILE
		SECURITY INVOKER
	AS $$
DECLARE
	rec		RECORD;
	mt_id	BIGINT;
BEGIN
	-- Lock all records
	PERFORM f.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 fleets.fleets f ON f.location_id = p.name_id
			INNER JOIN emp.empires e ON e.name_id = f.owner_id
		WHERE su.last_tick = c_tick AND su.status = 'PROCESSING'
					AND su.gu_type = 'PLANET_FLEET_STATUS'
		FOR UPDATE;

	-- Fleet deployments
	FOR rec IN SELECT f.id AS fleet , f.owner_id AS owner , f.location_id AS location ,
						b.id AS battle
					FROM sys.updates su
						INNER JOIN verse.updates vu ON vu.update_id = su.id
						INNER JOIN fleets.fleets f ON f.location_id = vu.planet_id
							AND f.status = 'DEPLOYING' AND f.penalty = 1
						INNER JOIN emp.empires e ON e.name_id = f.owner_id
						LEFT OUTER JOIN battles.battles b
							ON b.location_id = f.location_id AND b.last_tick IS NULL 
					WHERE su.last_tick = c_tick AND su.status = 'PROCESSING'
						AND su.gu_type = 'PLANET_FLEET_STATUS'
	LOOP
		-- Add fleet to battle (will be ignored if battle is NULL)
		PERFORM battles.add_fleet( rec.battle , rec.fleet , TRUE , c_tick );

		-- Find the biggest available fleet belonging to that owner
		SELECT INTO mt_id f.id
			FROM fleets.fleets f
				INNER JOIN fleets.ships s ON s.fleet_id = f.id
				INNER JOIN tech.ships sd ON sd.buildable_id = s.ship_id
				LEFT OUTER JOIN fleets.movements m ON m.fleet_id = f.id
			WHERE f.owner_id = rec.owner AND f.location_id = rec.location
				AND m.fleet_id IS NULL AND f.status = 'AVAILABLE'
			GROUP BY f.id
			ORDER BY sum( sd.power * s.amount ) DESC
			LIMIT 1;
		CONTINUE WHEN NOT FOUND;

		-- Merge fleet
		PERFORM fleets.merge_ships( mt_id , rec.fleet );
		DELETE FROM fleets.fleets WHERE id = rec.fleet;
	END LOOP;

	-- Fleets that must become available
	UPDATE fleets.fleets f SET status = 'AVAILABLE' , penalty = 0
		FROM sys.updates su , verse.updates vu
		WHERE vu.update_id = su.id AND f.location_id = vu.planet_id
			AND f.penalty = 1 AND su.status = 'PROCESSING'
			AND su.gu_type = 'PLANET_FLEET_STATUS' AND su.last_tick = c_tick;

	-- Fleets that still have a penalty
	UPDATE fleets.fleets f SET penalty = penalty - 1
		FROM sys.updates su , verse.updates vu
		WHERE vu.update_id = su.id AND f.location_id = vu.planet_id
			AND f.penalty > 1 AND su.status = 'PROCESSING'
			AND su.gu_type = 'PLANET_FLEET_STATUS' AND su.last_tick = c_tick;
END;
$$ LANGUAGE plpgsql;