/*
 * Utility functions used by unit tests
 *
 * Naming system
 */


/*
 * Obtain a map name identifier
 */
CREATE FUNCTION _get_map_name( TEXT ) RETURNS INT AS $$
	SELECT id FROM naming.map_names WHERE name = $1;
$$ LANGUAGE SQL;


/*
 * Obtain a map name identifier that does not exist
 */
CREATE FUNCTION _get_bad_map_name( ) RETURNS INT AS $$
	SELECT MAX( id ) + 1 FROM naming.map_names;
$$ LANGUAGE SQL;


/*
 * Create a few map names using a prefix
 */
CREATE FUNCTION _create_map_names( _quantity INT , _prefix TEXT )
		RETURNS VOID
	AS $$
DECLARE
	i	INT;
BEGIN
	i := 0;
	WHILE i < _quantity
	LOOP
		i := i + 1;
		BEGIN
			INSERT INTO naming.map_names (name) VALUES ( _prefix || i::TEXT );
		EXCEPTION
			WHEN unique_violation THEN
				-- Ignore the error
		END;
	END LOOP;
END;
$$ LANGUAGE PLPGSQL;


/*
 * Get the empire that belongs to some user, based on that user's email
 */
CREATE FUNCTION _get_emp_name( TEXT ) RETURNS INT AS $$
	SELECT id FROM naming.empire_names WHERE owner_id = _find_address( $1 );
$$ LANGUAGE SQL;


/*
 * Obtain a map name identifier that does not exist
 */
CREATE FUNCTION _get_bad_emp_name( ) RETURNS INT AS $$
	SELECT MAX( id ) + 1 FROM naming.empire_names;
$$ LANGUAGE SQL;


/*
 * Create a few empire names using a prefix for user accounts.
 * Empires are named "testX" independently of the user accounts.
 */
CREATE FUNCTION _create_emp_names( _quantity INT , _prefix TEXT )
		RETURNS VOID
	AS $$
DECLARE
	i	INT;
	j	INT;
BEGIN
	PERFORM _create_accounts( _quantity , _prefix );
	i := 0;
	WHILE i < _quantity
	LOOP
		i := i + 1;
		j := 0;
		LOOP
			BEGIN
				INSERT INTO naming.empire_names ( owner_id , name )
					VALUES ( _find_address( _prefix || i::TEXT ) , 'test' || j::TEXT );
				EXIT;
			EXCEPTION
				WHEN unique_violation THEN
					j := j + 1;
			END;
		END LOOP;
	END LOOP;
END;
$$ LANGUAGE PLPGSQL;