
CREATE OR REPLACE FUNCTION tcg.public.FN_TCG_MTG_Game_Round_Get_Many (
      a_get_all_game BOOLEAN
    , a_get_inactive_game BOOLEAN
	, a_game_ids TEXT
    , a_require_all_id_filters_met BOOLEAN
    , a_require_any_id_filters_met BOOLEAN
)
RETURNS TABLE (
      round_id INT
	, game_id INT
    , notes TEXT
    , display_order INT
    , active BOOLEAN
    , created_on TIMESTAMP
    , created_by_user_id INT
	, updated_last_on TIMESTAMP
	, updated_last_by_user_id INT
    , change_set_id INT
)
LANGUAGE plpgsql
AS $$
DECLARE
    v_get_all_game BOOLEAN;
    v_get_inactive_game BOOLEAN;
	v_game_ids TEXT;
    v_require_all_id_filters_met BOOLEAN;
    v_require_any_id_filters_met BOOLEAN;
BEGIN
	v_get_all_game := COALESCE(a_get_all_game, FALSE);
    v_get_inactive_game := COALESCE(a_get_inactive_game, FALSE);
	v_game_ids := TRIM(COALESCE(a_game_ids, ''));
    v_require_all_id_filters_met := COALESCE(a_require_all_id_filters_met, FALSE);
    v_require_any_id_filters_met := COALESCE(a_require_any_id_filters_met, FALSE);
	
	-- Outputs

    RETURN QUERY SELECT
          ROUND.round_id
        , ROUND.game_id
        , ROUND.notes
        , ROUND.display_order
        , ROUND.active
        , ROUND.created_on
        , ROUND.created_by_user_id
        , ROUND.updated_last_on
        , ROUND.updated_last_by_user_id
        , ROUND.change_set_id
    FROM tcg.public.TCG_MTG_Game_Round ROUND
    INNER JOIN tcg.public.TCG_MTG_Game GAME ON ROUND.game_id = GAME.game_id
    WHERE
            (
                (
                    NOT v_require_all_id_filters_met
                AND NOT v_require_any_id_filters_met
            )
            OR  (
                    v_require_all_id_filters_met
                AND (
                        v_get_all_game
                    OR  ROUND.game_id = ANY(string_to_array(v_game_ids, ',')::INT[])
                )
            )
            OR  (
                    NOT v_require_all_id_filters_met
                AND v_require_any_id_filters_met
                AND (
                        v_get_all_game
                    OR  ROUND.game_id = ANY(string_to_array(v_game_ids, ',')::INT[])
                )
            )
        )
        AND (
                v_get_inactive_game
            OR  ROUND.active
        )
	ORDER BY
          GAME.created_on DESC
        , ROUND.display_order
    ;
END;
$$;


SELECT *
FROM tcg.public.FN_TCG_MTG_Game_Round_Get_Many (
      a_get_all_game := FALSE
    , a_get_inactive_game := FALSE
    , a_game_ids := '11'
    , a_require_all_id_filters_met := TRUE 
    , a_require_any_id_filters_met := FALSE 
)
;


SELECT *
FROM tcg.public.TCG_MTG_Game
;
SELECT *
FROM tcg.public.TCG_MTG_Game_Round
;
