-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- Map display functions and related types
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------


-- Map entry
CREATE TYPE map_entry_type AS (
	x			INT ,
	y			INT ,
	orbit		INT ,
	id			INT ,
	picture		INT ,
	name		TEXT ,
	tag			TEXT ,
	display		empire_relation_type
);


--
-- Generates the map from an empire's point of view
--
-- Parameters:
--	e_id	the empire viewing the map
--	min_x	minimal X coordinate
--	min_y	minimal Y coordinate
--	max_x	maximal X coordinate
--	max_y	maximal Y coordinate
--
-- Returns:
--	a set of map entries
--

CREATE OR REPLACE FUNCTION verse.get_map( e_id INT , min_x INT , min_y INT , max_x INT , max_y INT )
	RETURNS SETOF map_entry_type
	STRICT STABLE
	SECURITY DEFINER
AS $$
	SELECT mv.x AS x , mv.y AS y , mv.orbit AS orbit , mv.id AS id , mv.picture AS picture ,
			mv.name AS name , mv.tag AS tag ,
			(CASE
				WHEN mv.owner = $1 THEN 'OWN'
				WHEN mv.alliance_id IS NOT NULL AND mv.alliance_id = ea.alliance_id THEN 'ALLIED'
				WHEN en.alliance_id IS NOT NULL THEN 'ENEMY'
				ELSE NULL
			END )::empire_relation_type AS display
		FROM verse.map_view mv
			LEFT OUTER JOIN emp.alliance_members ea
				ON ea.empire_id = $1 AND NOT is_pending
			LEFT OUTER JOIN emp.enemy_alliances en
				ON en.empire_id = $1 AND en.alliance_id = mv.alliance_id
		WHERE x BETWEEN $2 AND $4 AND y BETWEEN $3 AND $5;
$$ LANGUAGE SQL;

GRANT EXECUTE ON FUNCTION verse.get_map( INT , INT , INT , INT , INT ) TO :dbuser;
