-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- Game updates - damage fleets and buildings when an
-- empire is out of cash and has too much upkeep
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------



CREATE OR REPLACE FUNCTION sys.process_empire_debt_updates( c_tick BIGINT )
		RETURNS VOID
		STRICT VOLATILE
		SECURITY INVOKER
	AS $$
DECLARE
	fleet_dr	REAL;
	bld_dr		REAL;
	empire		INT;
	debt		REAL;
	upkeep		REAL;
BEGIN
	fleet_dr := sys.get_constant( 'game.debt.fleet');
	bld_dr := sys.get_constant( 'game.debt.buildings');

	FOR empire, debt IN SELECT e.name_id AS id , e.debt
					FROM sys.updates su
						INNER JOIN emp.updates eu ON eu.update_id = su.id
						INNER JOIN emp.empires e ON eu.empire_id = e.name_id
					WHERE su.last_tick = c_tick AND su.status = 'PROCESSING'
						AND su.gu_type = 'EMPIRE_DEBT' AND e.debt > 0
					FOR UPDATE
	LOOP
		PERFORM sys.write_log( 'EmpireDebt' , 'DEBUG'::log_level , 'Handling debt for empire #'
			|| empire || ' (at tick: ' || debt || '; daily: ' || ( debt * 1440 ) || ')' );
		debt := debt * 1440.0;

		-- Does the empire own fleets?
		SELECT INTO upkeep sum( d.upkeep * s.amount )
			FROM fleets.fleets f
				INNER JOIN fleets.ships s ON s.fleet_id = f.id
				INNER JOIN tech.buildables d ON d.name_id = s.ship_id
			WHERE f.owner_id = empire;
		IF upkeep IS NOT NULL
		THEN
			PERFORM fleets.handle_debt( empire , upkeep , ( CASE WHEN debt > upkeep THEN upkeep ELSE debt END ) , fleet_dr );
			debt := debt - upkeep;
			CONTINUE WHEN debt <= 0;
		END IF;
		
		-- Does the empire have buildings?
		SELECT INTO upkeep sum( d.upkeep * b.amount )
			FROM emp.planets ep
				INNER JOIN verse.planet_buildings b ON b.planet_id = ep.planet_id
				INNER JOIN tech.buildables d ON d.name_id = b.building_id
			WHERE ep.empire_id = empire;
		CONTINUE WHEN NOT FOUND OR upkeep = 0;
		PERFORM verse.handle_debt( empire , upkeep , debt , bld_dr );
	END LOOP;
END;
$$ LANGUAGE plpgsql;