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


/*
 * Empire resources update
 * 
 * For each empire in the update batch, compute the new amount of resources
 * based on the upkeep and income from planets.
 * 
 * FIXME: this should also include fleet upkeeps. This situation will be
 *        resolved once the system is modified to rely solely on resources.
 * 
 * Parameters:
 *		_tick		The identifier of the game update
 */
DROP FUNCTION IF EXISTS sys.process_empire_resources_updates( BIGINT );
CREATE FUNCTION sys.process_empire_resources_updates( _tick BIGINT )
	RETURNS VOID
	STRICT VOLATILE
	SECURITY INVOKER
AS $process_empire_resources_updates$

	UPDATE emp.resources _emp_resources

		SET empres_possessed = CASE
				WHEN _emp_resources.empres_possessed + _raw.res_delta > 0 THEN
					_emp_resources.empres_possessed + _raw.res_delta
				ELSE
					0
				END ,
			empres_owed = CASE
				WHEN _emp_resources.empres_possessed + _raw.res_delta < 0 THEN
					 -( _emp_resources.empres_possessed + _raw.res_delta ) 
				ELSE
					0
				END

		FROM (
			SELECT _upd_emp.name_id AS empire_id ,  _pl_resources.resource_name_id ,
					( _pl_resources.pres_income - _pl_resources.pres_upkeep ) / ( CASE
						WHEN _vacation.account_id IS NULL THEN
							1
						ELSE
							sys.get_constant( 'vacation.cashDivider' )
					END ) AS res_delta

				FROM sys.updates _upd_sys
					INNER JOIN emp.empires_updates _upd_emp
						USING ( updtgt_id , updtype_id , update_id )
					INNER JOIN emp.planets _emp_planets
						ON empire_id = name_id
					INNER JOIN verse.planet_resources _pl_resources
						USING ( planet_id )
					INNER JOIN naming.empire_names _emp_name
						ON _emp_name.id = _upd_emp.name_id
					LEFT OUTER JOIN users.vacations _vacation
						ON _vacation.account_id = _emp_name.owner_id
							AND _vacation.status = 'PROCESSED'

				WHERE _upd_sys.update_last = $1
					AND _upd_sys.update_state = 'PROCESSING'
			) _raw

		WHERE _emp_resources.empire_id = _raw.empire_id
			AND _emp_resources.resource_name_id = _raw.resource_name_id;

$process_empire_resources_updates$ LANGUAGE SQL;


REVOKE EXECUTE
	ON FUNCTION sys.process_empire_resources_updates( BIGINT )
	FROM PUBLIC;



SELECT sys.register_update_type( 'Empires' , 'EmpireResources' ,
		'Empires'' resources are being updated using the previous update''s results. ' ,
		'process_empire_resources_updates'
	);