/*
 * Test the verse.collect_resprov_statistics( ) function
 */
BEGIN;
	\i utils/strings.sql
	\i utils/resources.sql
	\i utils/accounts.sql
	\i utils/naming.sql
	\i utils/universe.sql
	SELECT _create_natural_resources( 2 , 'testResource' );
	SELECT _create_raw_planets( 5 , 'testPlanet' );

	/****** TESTS BEGIN HERE ******/
	SELECT plan( 6 );

	SELECT verse.collect_resprov_statistics( );
	
	SELECT diag_test_name( 'verse.collect_resprov_statistics( ) - Temporary table creation' );
	SELECT has_table( 'rp_stats' );

	SELECT diag_test_name( 'verse.collect_resprov_statistics( ) - Temporary table rows' );
	SELECT is( COUNT(*)::INT , 2 ) FROM rp_stats;

	SELECT diag_test_name( 'verse.collect_resprov_statistics( ) - rp_stats contains definition data' );
	SELECT is( COUNT(*)::INT , 2 )
		FROM (
			SELECT ( d.natres_quantity_avg = s.quantity_avg
					AND d.natres_quantity_dev = s.quantity_dev
					AND d.natres_difficulty_avg = s.difficulty_avg
					AND d.natres_difficulty_dev = s.difficulty_dev
					AND d.natres_recovery_avg = s.recovery_avg
					AND d.natres_recovery_dev = s.recovery_dev
					AND d.natres_p_presence = s.presence ) AS ok
				FROM rp_stats s
					INNER JOIN defs.natural_resources d
						USING ( resource_name_id )
			) sq
		WHERE sq.ok;

	SELECT diag_test_name( 'verse.collect_resprov_statistics( ) - rp_stats contains planet counts' );
	SELECT is( COUNT(*)::INT , 2 )
		FROM (
			SELECT planets = 5 AS ok
				FROM rp_stats
			) sq
		WHERE sq.ok;

	SELECT diag_test_name( 'verse.collect_resprov_statistics( ) - rp_stats sums at 0 with no providers' );
	SELECT is( COUNT(*)::INT , 2 )
		FROM (
			SELECT ( providers = 0 AND quantity = 0
					AND difficulty = 0 AND recovery = 0 ) AS ok
				FROM rp_stats
			) sq
		WHERE sq.ok;

	DROP TABLE rp_stats;
	SELECT _create_resource_provider( 'testPlanet1' , 'testResource1' );
	SELECT verse.collect_resprov_statistics( );

	SELECT diag_test_name( 'verse.collect_resprov_statistics( ) - rp_stats sums' );
	SELECT is( COUNT(*)::INT , 1 )
		FROM (
			SELECT ( resource_name_id = _get_string( 'testResource1' )
					AND providers = 1 AND quantity = 100
					AND difficulty = 0.5 AND recovery = 0.5 ) AS ok
				FROM rp_stats
			) sq
		WHERE sq.ok;

	SELECT * FROM finish( );
ROLLBACK;