/*
 * Test the verse.get_extraction_factor() function
 */
BEGIN;
	/* Drop foreign keys on resource providers, then fill the table with
	 * values which can be used to test some fundamental properties of
	 * the computation, then create a view that returns computation results.
	 */
	ALTER TABLE verse.resource_providers
		DROP CONSTRAINT fk_resprov_planet ,
		DROP CONSTRAINT fk_resprov_resource;

	CREATE FUNCTION _fill_providers( )
			RETURNS VOID
		AS $$
	DECLARE
		i	INT;
		j	INT;
	BEGIN
		FOR i IN 0 .. 10
		LOOP
			FOR j IN 0 .. 10
			LOOP
				INSERT INTO verse.resource_providers(
						planet_id , resource_name_id ,
						resprov_quantity_max , resprov_quantity ,
						resprov_difficulty , resprov_recovery
					) VALUES (
						i , j , 100 , j * 10 , i * 0.1 , 0.5
					);
			END LOOP;
		END LOOP;
	END;
	$$ LANGUAGE PLPGSQL;
	SELECT _fill_providers( );
	DROP FUNCTION _fill_providers( );
	
	CREATE VIEW extraction_factor_view
		AS SELECT planet_id , resource_name_id ,
				verse.get_extraction_factor(
					resprov_quantity / resprov_quantity_max ,
					resprov_difficulty
				) AS resprov_extraction
			FROM verse.resource_providers;
	
	
	/***** TESTS BEGIN HERE *****/
	SELECT plan( 6 );

	SELECT diag_test_name( 'verse.get_extraction_factor() - Range');
	SELECT is_empty($$
		SELECT * FROM extraction_factor_view
			WHERE resprov_extraction NOT BETWEEN 0 AND 1
	$$);

	SELECT diag_test_name( 'verse.get_extraction_factor() - Full provider with difficulty 0 => extraction is 1');
	SELECT is( resprov_extraction , 1.0::DOUBLE PRECISION )
		FROM extraction_factor_view
		WHERE planet_id = 0 AND resource_name_id = 10;
	SELECT diag_test_name( 'verse.get_extraction_factor() - Full provider with difficulty 1 => extraction is 0.5');
	SELECT is( resprov_extraction , 0.5::DOUBLE PRECISION )
		FROM extraction_factor_view
		WHERE planet_id = 10 AND resource_name_id = 10;
	SELECT diag_test_name( 'verse.get_extraction_factor() - Empty provider => extraction is 0');
	SELECT is_empty($$
		SELECT * FROM extraction_factor_view
			WHERE resource_name_id = 0 AND resprov_extraction > 0
	$$);

	SELECT diag_test_name( 'verse.get_extraction_factor() - At same quantity ratio, higher difficulty => lower extraction');
	SELECT is_empty($$
		SELECT * FROM extraction_factor_view v1
				INNER JOIN extraction_factor_view v2
					ON v1.resource_name_id = v2.resource_name_id
			WHERE v1.planet_id > v2.planet_id
				AND v1.resprov_extraction > v2.resprov_extraction
	$$);

	SELECT diag_test_name( 'verse.get_extraction_factor() - At same difficulty, higher quantity ratio => higher extraction');
	SELECT is_empty($$
		SELECT * FROM extraction_factor_view v1
				INNER JOIN extraction_factor_view v2
					ON v1.planet_id = v2.planet_id
			WHERE v1.resource_name_id > v2.resource_name_id
				AND v1.resprov_extraction < v2.resprov_extraction
	$$);

	SELECT * FROM finish( );
ROLLBACK;