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


CREATE OR REPLACE FUNCTION sys.process_empire_money_updates( c_tick BIGINT )
		RETURNS VOID
		STRICT VOLATILE
		SECURITY INVOKER
	AS $$
DECLARE
	rec		RECORD;
	c_cash	REAL;
	c_debt	REAL;
BEGIN
	-- Lock empires for update
	PERFORM e.name_id 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_MONEY'
		FOR UPDATE OF e;

	-- Select all money-related data from empires being updated
	FOR rec IN SELECT e.name_id AS id , e.cash AS cash , e.debt AS debt ,
						( pov.planet_income - pov.planet_upkeep ) AS p_money ,
						fov.fleet_upkeep AS f_money , ( v.status = 'PROCESSED' ) AS on_vacation
					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
						INNER JOIN emp.fleets_overview fov ON fov.empire = e.name_id
						INNER JOIN emp.planets_overview pov ON pov.empire = e.name_id
						INNER JOIN naming.empire_names en ON en.id = e.name_id
						LEFT OUTER JOIN users.vacations v ON v.account_id = en.owner_id
					WHERE su.last_tick = c_tick AND su.status = 'PROCESSING'
						AND su.gu_type = 'EMPIRE_MONEY'
	LOOP
		-- Compute new cash reserve
		c_cash := 0;
		IF rec.p_money IS NOT NULL THEN
			c_cash := c_cash + rec.p_money;
		END IF;
		IF rec.f_money IS NOT NULL THEN
			c_cash := c_cash - rec.f_money;
		END IF;

		-- Effects of vacation mode
		IF rec.on_vacation
		THEN
			c_cash := c_cash / sys.get_constant( 'vacation.cashDivider' );
		END IF;

		-- Handle debt
		c_cash := rec.cash + c_cash / 1440.0;
		IF c_cash < 0 THEN
			c_debt := -c_cash;
			c_cash := 0;
		ELSE
			c_debt := 0;
		END IF;
		
		IF rec.debt > 0 AND c_debt = 0
		THEN
			PERFORM events.debt_event( rec.id , FALSE );
		ELSEIF rec.debt = 0 AND c_debt > 0
		THEN
			PERFORM events.debt_event( rec.id , TRUE );
		END IF;

		-- Update empire
		UPDATE emp.empires SET cash = c_cash , debt = c_debt
			WHERE name_id = rec.id;
	END LOOP;
END;
$$ LANGUAGE plpgsql;