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


CREATE OR REPLACE FUNCTION sys.process_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.planets_updates vu
				USING ( update_id , updtype_id , updtgt_id )
			INNER JOIN verse.planets p
				USING ( name_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.update_last = c_tick AND su.update_state = 'PROCESSING'
		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.planets_updates vu
							USING ( update_id , updtype_id , updtgt_id )
						INNER JOIN fleets.fleets f ON f.location_id = vu.name_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.update_last = c_tick AND su.update_state = 'PROCESSING'
	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.planets_updates vu
		WHERE vu.update_id = su.update_id AND f.location_id = vu.name_id
			AND f.penalty = 1
			AND su.update_state = 'PROCESSING' AND su.update_last = c_tick;

	-- Fleets that still have a penalty
	UPDATE fleets.fleets f SET penalty = penalty - 1
		FROM sys.updates su , verse.planets_updates vu
		WHERE vu.update_id = su.update_id AND f.location_id = vu.name_id
			AND f.penalty > 1
			AND su.update_state = 'PROCESSING' AND su.update_last = c_tick;
END;
$$ LANGUAGE plpgsql;

SELECT sys.register_update_type( 'Planets' , 'FleetStatus' ,
		'Fleet states (e.g. "deploying", "unavailable", etc...) are being  updated.' ,
		'process_fleet_status_updates'
	);