 
USE parts;

DROP PROCEDURE IF EXISTS parts.p_dog_calc_bribe;

DELIMITER //
CREATE PROCEDURE parts.p_dog_calc_bribe (
      IN a_guid BINARY(36)
    , IN a_id_user INT
    , IN a_get_all_bribe BIT
	, IN a_get_inactive_bribe BIT
	, IN a_ids_bribe TEXT
    , IN a_names_bribe TEXT
    , IN a_require_all_id_search_filters_met BIT
    , IN a_require_any_id_search_filters_met BIT
    , IN a_require_all_non_id_search_filters_met BIT
    , IN a_require_any_non_id_search_filters_met BIT
    , IN a_show_errors BIT
    , IN a_debug BIT
)
BEGIN
    DECLARE v_can_view BIT;
    DECLARE v_code_type_error_bad_data VARCHAR(100);
    DECLARE v_code_type_error_no_permission VARCHAR(100);
    DECLARE v_has_filter_bribe_id BIT;
    DECLARE v_has_filter_bribe_name BIT;
    DECLARE v_id_access_level_view INT;
    DECLARE v_id_minimum INT;
    DECLARE v_id_permission_dog_view INT;
    DECLARE v_id_type_error_bad_data INT;
    DECLARE v_id_type_error_no_permission INT;
    DECLARE v_time_start TIMESTAMP(6);
    
    DECLARE exit handler for SQLEXCEPTION
    BEGIN
        GET DIAGNOSTICS CONDITION 1
            @sqlstate = RETURNED_SQLSTATE
            , @errno = MYSQL_ERRNO
            , @text = MESSAGE_TEXT
		;
        
        ROLLBACK;
        
		CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error_Calc_Bribe (
			  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT
			, code VARCHAR(250) NOT NULL
			, msg TEXT NOT NULL
		);

        INSERT INTO tmp_Msg_Error_Calc_Bribe (
			  id_type
            , code
            , msg
		)
        SELECT 
			  MET.id_type
            , @errno
            , @text
		FROM parts.CORE_Msg_Error_Type MET
        WHERE MET.code = 'MYSQL_ERROR'
		;
        
        SELECT 
            t_ERROR.id_error
            , t_ERROR.id_type
            , t_ERROR.code
            , ERROR_TYPE.name
            , ERROR_TYPE.description
            , ERROR_TYPE.is_breaking_error
            , ERROR_TYPE.background_colour
            , ERROR_TYPE.text_colour
            , t_ERROR.msg
        FROM tmp_Msg_Error_Calc_Bribe t_ERROR
        INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
        ;
        
		DROP TABLE IF EXISTS tmp_Msg_Error_Calc_Bribe;
    END;

    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_code_type_error_bad_data := 'BAD_DATA';
    SET v_code_type_error_no_permission := 'NO_PERMISSION';
    SET v_id_type_error_bad_data := (SELECT ERROR_TYPE.id_type FROM parts.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_bad_data LIMIT 1);
    SET v_id_type_error_no_permission := (SELECT ERROR_TYPE.id_type FROM parts.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_no_permission LIMIT 1);
    SET v_id_permission_dog_view := (SELECT PERMISSION.id_permission FROM parts.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_VIEW' LIMIT 1);
    SET v_id_access_level_view := (SELECT ACCESS_LEVEL.id_access_level FROM parts.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'VIEW' LIMIT 1);
    
    
    CALL parts.p_core_validate_guid ( a_guid );

    SET a_id_user := IFNULL(a_id_user, 0);
    SET a_get_all_bribe := IFNULL(a_get_all_bribe, 0);
    SET a_get_inactive_bribe := IFNULL(a_get_inactive_bribe, 0);
    SET a_ids_bribe := TRIM(IFNULL(a_ids_bribe, ''));
    SET a_names_bribe := TRIM(IFNULL(a_names_bribe, ''));
    SET a_require_all_id_search_filters_met := IFNULL(a_require_all_id_search_filters_met, 1);
    SET a_require_any_id_search_filters_met := IFNULL(a_require_any_id_search_filters_met, 1);
    SET a_require_all_non_id_search_filters_met := IFNULL(a_require_all_non_id_search_filters_met, 0);
    SET a_require_any_non_id_search_filters_met := IFNULL(a_require_any_non_id_search_filters_met, 1);
    SET a_show_errors := IFNULL(a_show_errors, 0);
    SET a_debug := IFNULL(a_debug, 0);
    
    IF a_debug = 1 THEN
		SELECT 
              a_guid
			, a_id_user
            , a_get_all_bribe
            , a_get_inactive_bribe
            , a_ids_bribe
            , a_names_bribe
            , a_require_all_id_search_filters_met
            , a_require_any_id_search_filters_met
            , a_require_all_non_id_search_filters_met
            , a_require_any_non_id_search_filters_met
            , a_show_errors
            , a_debug
		;

        SELECT
              v_id_type_error_bad_data
            , v_id_type_error_no_permission
            , v_id_permission_dog_view
            , v_time_start
        ;
    END IF;

    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Name_Calc_Bribe;
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Id_Calc_Bribe;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error_Calc_Bribe;
    DROP TEMPORARY TABLE IF EXISTS tmp_Bribe_Calc_Bribe;
    
    CREATE TEMPORARY TABLE tmp_Bribe_Calc_Bribe (
		  id_bribe INT NOT NULL
        , does_meet_id_filters BIT NOT NULL
        , does_meet_non_id_filters BIT NOT NULL
    );

	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error_Calc_Bribe (
          id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT
		, code VARCHAR(250) NOT NULL
        , msg TEXT NOT NULL
	);
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Id_Calc_Bribe (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Id_Calc_Bribe;
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Name_Calc_Bribe (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Name_Calc_Bribe;
    
    SET v_has_filter_bribe_id = CASE WHEN a_ids_bribe <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_bribe_name = CASE WHEN a_names_bribe <> '' THEN 1 ELSE 0 END;

    -- Bribes
    IF v_has_filter_bribe_id = 1 THEN
		CALL parts.p_core_split(a_guid, a_ids_bribe, ',', a_debug);

        SET sql_mode = '';
		
		INSERT INTO tmp_Split_Id_Calc_Bribe (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CAST(SPLIT_T.substring AS DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp SPLIT_T
		WHERE 
                SPLIT_T.GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') <> ''
		;
		
		CALL parts.p_core_clear_split( a_guid );
	END IF;

    IF v_has_filter_bribe_name = 1 THEN
		CALL parts.p_core_split(a_guid, a_names_bribe, ',', a_debug);

        SET sql_mode = '';
		
		INSERT INTO tmp_Split_Name_Calc_Bribe (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CAST(SPLIT_T.substring AS DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp SPLIT_T
		WHERE 
                SPLIT_T.GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') <> ''
		;
		
		CALL parts.p_core_clear_split( a_guid );
	END IF;
    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_Bribe t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
		IF EXISTS (
			SELECT * 
            FROM tmp_Split_Id_Calc_Bribe t_SPLIT_ID
            LEFT JOIN parts.DOG_Bribe BRIBES ON t_SPLIT_ID.as_int = BRIBES.id_bribe 
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
                OR  ISNULL(BRIBES.id_bribe)
				OR  (
					BRIBES.active = 0
					AND a_get_inactive_bribe = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error_Calc_Bribe (
				  id_type
		        , code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive Bribe IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT_ID.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split_Id_Calc_Bribe t_SPLIT_ID
			LEFT JOIN parts.DOG_Bribe BRIBES ON t_SPLIT_ID.as_int = BRIBES.id_bribe
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
				OR  ISNULL(BRIBES.id_bribe)
				OR  (
					BRIBES.active = 0
					AND a_get_inactive_bribe = 0
				)
			;
        /* Don't error on names, hand signals, or notes not found
		ELSEIF EXISTS ()
        */
		ELSE
			INSERT INTO tmp_Bribe_Calc_Bribe (
				  id_bribe
                , does_meet_id_filters
                , does_meet_non_id_filters
			)
            WITH 
                  Bribe_Id_Filter AS (
                    SELECT BRIBES.id_bribe
                    FROM tmp_Split_Id_Calc_Bribe t_SPLIT_ID
                    INNER JOIN parts.DOG_Bribe BRIBES ON t_SPLIT_ID.as_int = BRIBES.id_bribe
                )
                , Bribe_Name_Filter AS (
                    SELECT BRIBES.id_bribe
                    FROM tmp_Split_Name_Calc_Bribe t_SPLIT_NAME
                    INNER JOIN parts.DOG_Bribe BRIBES ON BRIBES.name LIKE CONCAT('%', t_SPLIT_NAME.substring, '%')
                    WHERE NULLIF(t_SPLIT_NAME.substring, '') IS NOT NULL
                )
                , Bribe_Filters AS (
                    SELECT 
                          BRIBES_COMBINED.id_bribe
                        , MAX(BRIBES_COMBINED.does_meet_id_filter) AS does_meet_id_filter
                        , MAX(BRIBES_COMBINED.does_meet_name_filter) AS does_meet_name_filter
                    FROM (
                        SELECT 
                              BRIBES_ID_FILTER.id_bribe 
                            , 1 AS does_meet_id_filter
                            , 0 AS does_meet_name_filter
                        FROM Bribe_Id_Filter BRIBES_ID_FILTER
                        UNION
                        SELECT 
                              BRIBES_NAME_FILTER.id_bribe 
                            , 0 AS does_meet_id_filter
                            , 1 AS does_meet_name_filter
                        FROM Bribe_Name_Filter BRIBES_NAME_FILTER
                    ) BRIBES_COMBINED
                    GROUP BY BRIBES_COMBINED.id_bribe
                )
            SELECT 
                  BRIBES.id_bribe
                , CASE WHEN 
                        v_has_filter_bribe_id = 0 
                    OR  IFNULL(BRIBES_FILTERS.does_meet_id_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_id_filters
                , CASE WHEN 
                        (
                            v_has_filter_bribe_name = 0
                    )
                    OR  IFNULL(BRIBES_FILTERS.does_meet_name_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_non_id_filters
            FROM parts.DOG_Bribe BRIBES
            LEFT JOIN Bribe_Filters BRIBES_FILTERS ON BRIBES.id_bribe = BRIBES_FILTERS.id_bribe
            WHERE 
                (
                        a_get_all_bribe = 1
                    OR  (
                            v_has_filter_bribe_id = 1
                        AND BRIBES_FILTERS.does_meet_id_filter = 1
                    )
                    OR  (
                            v_has_filter_bribe_name = 1
                        AND BRIBES_FILTERS.does_meet_name_filter = 1
                    )
                )
                AND (
                        a_get_inactive_bribe = 1
                    OR  BRIBES.active = 1
                )
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split_Id_Calc_Bribe;
    DELETE FROM tmp_Split_Name_Calc_Bribe;

    IF a_debug = 1 THEN
        SELECT 'After get Bribes ';
        SELECT * FROM tmp_Bribe_Calc_Bribe;
    END IF;

    -- Filter records
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_Bribe t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
        DELETE t_BRIBES
        FROM tmp_Bribe_Calc_Bribe t_BRIBES
        WHERE
                (
                    a_require_all_id_search_filters_met = 1
                AND (
                        t_BRIBES.does_meet_id_filters = 0
                )
            )
            OR  (
                    a_require_all_non_id_search_filters_met = 1
                AND (
                        t_BRIBES.does_meet_non_id_filters = 0
                )
            )
            OR  (
                a_require_any_id_search_filters_met = 1
                AND t_BRIBES.does_meet_id_filters = 0
            )
            OR  (
                a_require_any_non_id_search_filters_met = 1
                AND t_BRIBES.does_meet_non_id_filters = 0
            )
        ;
    END IF;

    IF a_debug = 1 THEN
        SELECT 'After filter Bribes';
        SELECT * FROM tmp_Bribe_Calc_Bribe;
    END IF;

    -- Calculated fields

    -- Permissions
    IF a_debug = 1 THEN
		SELECT 
			  a_guid -- a_guid
            , 0 -- get_all_user
            , 0 -- get_inactive_user
            , a_id_user -- ids_user
            , '' -- a_auth0_ids_user
            , '' -- a_names_user
            , '' -- a_emails_user
            , 1 -- a_require_all_id_search_filters_met
            , 1 -- a_require_any_id_search_filters_met
            , 0 -- a_require_all_non_id_search_filters_met
            , 0 -- a_require_any_non_id_search_filters_met
            , v_id_permission_dog_view -- ids_permission
            , v_id_access_level_view -- ids_access_level
            , 0 -- a_show_errors
			, 0 -- a_debug
        ;
    END IF;
    
	CALL parts.p_dog_calc_user(
          a_guid -- a_guid
        , 0 -- get_all_user
        , 0 -- get_inactive_user
        , a_id_user -- ids_user
        , '' -- a_auth0_ids_user
        , '' -- a_names_user
        , '' -- a_emails_user
        , 1 -- a_require_all_id_search_filters_met
        , 1 -- a_require_any_id_search_filters_met
        , 0 -- a_require_all_non_id_search_filters_met
        , 0 -- a_require_any_non_id_search_filters_met
        , v_id_permission_dog_view -- ids_permission
        , v_id_access_level_view -- ids_access_level
        , 0 -- a_show_errors
        , 0 -- a_debug
    );
	
    SELECT
          IFNULL(CALC_USER_T.has_access, 0)
    INTO
          v_can_view
    FROM parts.DOG_Calc_User_Temp CALC_USER_T
    WHERE CALC_USER_T.GUID = a_guid
    LIMIT 1
    ;
    
    IF a_debug = 1 THEN
        SELECT v_can_view;
    END IF;
    
    IF (v_can_view = 0) THEN
		DELETE t_ME
        FROM tmp_Msg_Error_Calc_Bribe t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error_Calc_Bribe (
			  id_type
			, code
            , msg
		)
		VALUES (
			  v_id_type_error_no_permission
            , v_code_type_error_no_permission
			, 'You do not have permission to view Dogs and Bribes.'
		)
        ;
    END IF;
	
	CALL parts.p_dog_clear_calc_user(
		a_guid
        , 0 -- a_debug
	);

    IF a_debug = 1 THEN
        SELECT 'Before non-permitted data deletion';
        SELECT * FROM tmp_Bribe_Calc_Bribe;
        SELECT * FROM tmp_Msg_Error_Calc_Bribe;
    END IF;
    
    IF EXISTS(SELECT * FROM tmp_Msg_Error_Calc_Bribe t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
        IF a_debug = 1 THEN
            SELECT * FROM tmp_Bribe_Calc_Bribe;
        END IF;

        DELETE FROM tmp_Bribe_Calc_Bribe;
    END IF;

    IF a_debug = 1 THEN
        SELECT 'After non-permitted data deletion';
    END IF;

    -- Outputs
	START TRANSACTION;
        -- Bribes
        INSERT INTO parts.DOG_Bribe_Temp (
              guid
            , id_bribe
            , code
            , name
            , active

            , does_meet_id_filters
            , does_meet_non_id_filters
        )
        SELECT 
              a_guid
            , t_BRIBES.id_bribe
            , BRIBES.code
            , BRIBES.name
            , BRIBES.active

            , t_BRIBES.does_meet_id_filters
            , t_BRIBES.does_meet_non_id_filters
        FROM parts.DOG_Bribe BRIBES
        INNER JOIN tmp_Bribe_Calc_Bribe t_BRIBES ON BRIBES.id_bribe = t_BRIBES.id_bribe
        ORDER BY BRIBES.name
        ;
    COMMIT;

    -- Errors
    IF a_show_errors = 1 THEN
        SELECT 
            t_ERROR.id_error
            , t_ERROR.id_type
            , t_ERROR.code
            , ERROR_TYPE.name
            , ERROR_TYPE.description
            , ERROR_TYPE.is_breaking_error
            , ERROR_TYPE.background_colour
            , ERROR_TYPE.text_colour
            , t_ERROR.msg
        FROM tmp_Msg_Error_Calc_Bribe t_ERROR
        INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
        ;
    END IF;

    IF a_debug = 1 AND v_can_view = 1 THEN
        SELECT * FROM tmp_Bribe_Calc_Bribe;
    END IF;
    
    CALL parts.p_dog_clear_calc_dog ( a_guid, 0 );

    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Name_Calc_Bribe;
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Id_Calc_Bribe;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error_Calc_Bribe;
    DROP TEMPORARY TABLE IF EXISTS tmp_Bribe_Calc_Bribe;
    
    IF a_debug = 1 THEN
		CALL parts.p_core_debug_timing_reporting ( v_time_start );
    END IF;
END //
DELIMITER ;


/*


CALL parts.p_dog_calc_bribe (
      'gripe                               ' -- a_guid
	, 1 -- 'auth0|6582b95c895d09a70ba10fef',	-- a_id_user
    , 1                                     	-- a_get_all_bribe
	, 0                                     	-- a_get_inactive_bribe
	, ''                                    	-- a_ids_bribe
    , ''                                        -- a_names_bribe
    , 0                                         -- a_require_all_id_search_filters_met
    , 0                                         -- a_require_any_id_search_filters_met
    , 0                                         -- a_require_all_non_id_search_filters_met
    , 0                                         -- a_require_any_non_id_search_filters_met
    , 0                                         -- a_show_errors
    , 0                                     	-- a_debug
);

SELECT *
FROM parts.DOG_Bribe_Temp
;
/*
SELECT *
FROM parts.DOG_Bribe_Temp C
WHERE 
        C.does_meet_id_filters
    AND C.does_meet_non_id_filters
;
*/
CALL parts.p_dog_clear_calc_bribe (
	'gripe                               ' -- a_guid
    , 1 -- debug
);


DELETE
FROM parts.DOG_Bribe_Temp
;

*/
