-- LegacyWorlds Beta 6
-- PostgreSQL database scripts
--
-- Definitions management functions
--
-- Copyright(C) 2004-2010, DeepClone Development
-- --------------------------------------------------------

--
-- Creates or updates a language definition
--
-- Parameters:
--	lid		Language identifier
--	lnm		Language name
--

CREATE OR REPLACE FUNCTION defs.uoc_language( lid TEXT , lnm TEXT )
		RETURNS VOID
		STRICT
		VOLATILE
		SECURITY DEFINER
	AS $$
BEGIN
	INSERT INTO defs.languages ( language , name )
		VALUES ( lower( lid ) , lnm );
EXCEPTION
	WHEN unique_violation THEN
		UPDATE defs.languages SET name = lnm
			WHERE language = lower( lid );
END;
$$ LANGUAGE plpgsql;

GRANT EXECUTE ON FUNCTION defs.uoc_language( TEXT , TEXT ) TO :dbuser;


CREATE OR REPLACE FUNCTION defs.uoc_language( lid TEXT , lnm TEXT , a_id INT )
		RETURNS VOID
		STRICT VOLATILE
		SECURITY DEFINER
	AS $$
BEGIN
	PERFORM admin.write_log( a_id , 'INFO'::log_level , 'Updating language ' || lid );
	PERFORM defs.uoc_language( lid , lnm );
END;
$$ LANGUAGE plpgsql;

GRANT EXECUTE ON FUNCTION defs.uoc_language( TEXT, TEXT , INT ) TO :dbuser;


--
-- Creates or updates a translation
--
-- Parameters:
--	lid		Language identifier
--	sid		String identifier
--	txt		Translation
--

CREATE OR REPLACE FUNCTION defs.uoc_translation( lid TEXT , sid TEXT , txt TEXT )
		RETURNS VOID
		STRICT
		VOLATILE
		SECURITY DEFINER
	AS $$
DECLARE
	isid	INT;
	ilid	INT;
BEGIN
	-- Get language
	SELECT INTO ilid id FROM defs.languages
		WHERE language = lid;

	-- Create string, if needed
	BEGIN
		INSERT INTO defs.strings (name) VALUES ( sid )
			RETURNING id INTO isid;
	EXCEPTION
		WHEN unique_violation THEN
			SELECT INTO isid id FROM defs.strings
				WHERE name = sid;
	END;
	
	-- Create or update translation
	BEGIN
		INSERT INTO defs.translations ( string_id , lang_id , translated_string )
			VALUES ( isid , ilid , txt );
	EXCEPTION
		WHEN unique_violation THEN
			UPDATE defs.translations SET translated_string = txt
				WHERE string_id = isid AND lang_id = ilid;
	END;
END;
$$ LANGUAGE plpgsql;

GRANT EXECUTE ON FUNCTION defs.uoc_translation( TEXT , TEXT , TEXT ) TO :dbuser;


CREATE OR REPLACE FUNCTION defs.uoc_translation( lid TEXT , sid TEXT , txt TEXT , a_id INT )
		RETURNS VOID
		STRICT VOLATILE
		SECURITY DEFINER
	AS $$
BEGIN
	PERFORM admin.write_log( a_id , 'INFO'::log_level , 'Updating string ' || sid || ' in language ' || lid );
	PERFORM defs.uoc_translation( lid , sid , txt );
END;
$$ LANGUAGE plpgsql;

GRANT EXECUTE ON FUNCTION defs.uoc_translation( TEXT, TEXT , TEXT , INT ) TO :dbuser;



--
-- Translations view (used to load all translations)
--

CREATE VIEW defs.translations_view
	AS SELECT l.language AS language_id , l.name AS language_name ,
			s.name AS string_id , t.translated_string AS translation
		FROM defs.translations t
			INNER JOIN defs.strings s
				ON s.id = t.string_id
			INNER JOIN defs.languages l
				ON l.id = t.lang_id;

GRANT SELECT ON defs.translations_view TO :dbuser;


