 
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_calc_image;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_calc_image (
      IN a_guid BINARY(36)
    , IN a_id_user INT
    , IN a_get_all_file_type BIT
	, IN a_get_inactive_file_type BIT
	, IN a_ids_file_type TEXT
    , IN a_names_file_type TEXT
    , IN a_get_all_dog BIT
	, IN a_get_inactive_dog BIT
	, IN a_ids_dog TEXT
    , IN a_names_dog TEXT
    , IN a_get_all_image BIT
	, IN a_get_inactive_image BIT
	, IN a_ids_image TEXT
    , IN a_names_image TEXT
    , IN a_get_all_user BIT
    , IN a_get_inactive_user BIT
    , IN a_ids_user TEXT
    , IN a_names_user TEXT
    , IN a_emails_user 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_file_type_id BIT;
    DECLARE v_has_filter_file_type_name BIT;
    DECLARE v_has_filter_image_id BIT;
    DECLARE v_has_filter_image_name BIT;
    DECLARE v_id_access_level_view INT;
    DECLARE v_id_minimum INT;
    DECLARE v_id_permission_command_view 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_ids_permission_required VARCHAR(200);
    DECLARE v_is_super_user BIT;
    DECLARE v_priority_access_level_none INT;
    DECLARE v_priority_access_level_view 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_Image (
			  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_Image (
			  id_type
            , code
            , msg
		)
        SELECT 
			  MET.id_type
            , @errno
            , @text
		FROM fetchmetrics.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_Image t_ERROR
        INNER JOIN fetchmetrics.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
        ;
        
		DROP TABLE IF EXISTS tmp_Msg_Error_Calc_Image;
    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 fetchmetrics.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 fetchmetrics.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_no_permission LIMIT 1);
    SET v_id_permission_command_view := (SELECT PERMISSION.id_permission FROM fetchmetrics.DOG_Permission PERMISSION WHERE PERMISSION.code = 'COMMAND_VIEW' LIMIT 1);
    SET v_id_permission_dog_view := (SELECT PERMISSION.id_permission FROM fetchmetrics.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_VIEW' LIMIT 1);
    SET v_id_access_level_view := (SELECT ACCESS_LEVEL.id_access_level FROM fetchmetrics.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'VIEW' LIMIT 1);
    SET v_ids_permission_required := (SELECT CONCAT(
        CONVERT(v_id_permission_dog_view, CHAR)
        , ','
        , CONVERT(v_id_permission_command_view, CHAR)
    ));
    SET v_priority_access_level_none := (SELECT ACCESS_LEVEL.priority FROM fetchmetrics.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'NONE' LIMIT 1);
    SET v_priority_access_level_view := (SELECT ACCESS_LEVEL.priority FROM fetchmetrics.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.id_access_level = v_id_access_level_view);

    CALL fetchmetrics.p_core_validate_guid ( a_guid );

    SET a_id_user := IFNULL(a_id_user, 0);
    -- SET a_get_all_dog := IFNULL(a_get_all_dog, 0);
    -- SET a_get_inactive_dog := IFNULL(a_get_inactive_dog, 0);
    -- SET a_ids_dog := TRIM(IFNULL(a_ids_dog, ''));
    -- SET a_names_dog := TRIM(IFNULL(a_names_dog, ''));
    SET a_get_all_file_type := IFNULL(a_get_all_file_type, 0);
    SET a_get_inactive_file_type := IFNULL(a_get_inactive_file_type, 0);
    SET a_ids_file_type := TRIM(IFNULL(a_ids_file_type, ''));
    SET a_names_file_type := TRIM(IFNULL(a_names_file_type, ''));
    SET a_get_all_image := IFNULL(a_get_all_image, 0);
    SET a_get_inactive_image := IFNULL(a_get_inactive_image, 0);
    SET a_ids_image := TRIM(IFNULL(a_ids_image, ''));
    SET a_names_image := TRIM(IFNULL(a_names_image, ''));
    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_file_type
            , a_get_inactive_file_type
            , a_ids_file_type
            , a_names_file_type
            , a_get_all_dog
            , a_get_inactive_dog
            , a_ids_dog
            , a_names_dog
            , a_get_all_image
            , a_get_inactive_image
            , a_ids_image
            , a_names_image
            , a_get_all_user
            , a_get_inactive_user
            , a_ids_user
            , a_names_user
            , a_emails_user
            , 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_command_view
            , v_id_permission_dog_view
            , v_ids_permission_required
            , v_time_start
        ;
    END IF;

    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Name_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Id_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Image_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Dog_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_File_Type_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Calc_User_Access_Calc_Image;
    
	CREATE TEMPORARY TABLE tmp_Calc_User_Access_Calc_Image (
		  id_temp INT PRIMARY KEY AUTO_INCREMENT NOT NULL
		, id_user INT
        , id_role INT
		, id_permission_required INT NOT NULL
		, priority_access_level_required INT NOT NULL
        , is_super_user BIT
		, priority_access_level_user INT
		, has_access BIT
		, can_view BIT
		, can_edit BIT
		, can_admin BIT
        , active BIT

        , does_meet_id_filters BIT
        , does_meet_non_id_filters BIT
	);
    
    CREATE TEMPORARY TABLE tmp_File_Type_Calc_Image (
		  id_file_type INT NOT NULL
        , does_meet_id_filters BIT NOT NULL
        , does_meet_non_id_filters BIT NOT NULL
    );
    
    CREATE TEMPORARY TABLE tmp_Dog_Calc_Image (
		  id_dog INT NOT NULL
        , active BIT

        , does_meet_id_filters BIT NOT NULL
        , does_meet_non_id_filters BIT NOT NULL
    );
    
    CREATE TEMPORARY TABLE tmp_Image_Calc_Image (
		  id_image INT NOT NULL
	    , id_file_type INT NOT NULL
        , exists_valid_link BIT NOT NULL
        , id_user INT
        , 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_Image (
          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_Image (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Id_Calc_Image;
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Name_Calc_Image (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Name_Calc_Image;
    
    SET v_has_filter_file_type_id = CASE WHEN a_ids_file_type <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_file_type_name = CASE WHEN a_names_file_type <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_image_id = CASE WHEN a_ids_image <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_image_name = CASE WHEN a_names_image <> '' THEN 1 ELSE 0 END;

    -- 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_ids_permission_required -- ids_permission
            , v_id_access_level_view -- ids_access_level
            , 0 -- a_show_errors
			, 0 -- a_debug
        ;
    END IF;
    
	CALL fetchmetrics.p_dog_calc_user_access(
          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_ids_permission_required -- 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)
        , IFNULL(CALC_USER_T.is_super_user, 0)
    INTO
          v_can_view
        , v_is_super_user
    FROM fetchmetrics.DOG_Calc_User_Access_Temp CALC_USER_T
    WHERE CALC_USER_T.GUID = a_guid
    LIMIT 1
    ;
    
    IF a_debug = 1 THEN
        SELECT 
            v_can_view
            , v_is_super_user
        ;
    END IF;
    
    IF (v_can_view = 0) THEN
		DELETE t_ME
        FROM tmp_Msg_Error_Calc_Image t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error_Calc_Image (
			  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 Images.'
		)
        ;
    END IF;
	
	CALL fetchmetrics.p_dog_clear_calc_user_access(
		a_guid
        , 0 -- a_debug
	);

    -- Users
    IF a_debug = 1 THEN
		SELECT 
			  a_guid -- guid
            , a_get_all_user -- get_all_user
            , a_get_inactive_user -- get_inactive_user
            , a_ids_user -- ids_user
            , '' -- a_auth0_ids_user
            , a_names_user -- a_names_user
            , a_emails_user -- a_emails_user
            , a_require_all_id_search_filters_met -- a_require_all_id_search_filters_met
            , 0 -- a_require_any_id_search_filters_met
            , a_require_all_non_id_search_filters_met -- a_require_all_non_id_search_filters_met
            , 0 -- a_require_any_non_id_search_filters_met
            , v_ids_permission_required -- ids_permission
            , v_id_access_level_view -- ids_access_level
            , 0 -- a_show_errors
			, 0 -- a_debug
        ;
    END IF;
    
	CALL fetchmetrics.p_dog_calc_user_access(
          a_guid-- guid
        , a_get_all_user -- get_all_user
        , a_get_inactive_user -- get_inactive_user
        , a_ids_user -- ids_user
        , '' -- a_auth0_ids_user
        , a_names_user -- a_names_user
        , a_emails_user -- a_emails_user
        , a_require_all_id_search_filters_met -- a_require_all_id_search_filters_met
        , 0 -- a_require_any_id_search_filters_met
        , a_require_all_non_id_search_filters_met -- a_require_all_non_id_search_filters_met
        , 0 -- a_require_any_non_id_search_filters_met
        , v_ids_permission_required -- ids_permission
        , v_id_access_level_view -- ids_access_level
        , 0 -- a_show_errors
        , 0 -- a_debug
    );
    
    INSERT INTO tmp_Calc_User_Access_Calc_Image (
        id_user
        , id_role
		, id_permission_required
		, priority_access_level_required
        , is_super_user
		, priority_access_level_user
		, has_access
		, can_view
		, can_edit
		, can_admin
        , active
        , does_meet_id_filters
        , does_meet_non_id_filters
    )
    SELECT
        CALC_USER_T.id_user
        , CALC_USER_T.id_role
		, CALC_USER_T.id_permission_required
		, CALC_USER_T.priority_access_level_required
        , CALC_USER_T.is_super_user
		, CALC_USER_T.priority_access_level_user
		, CALC_USER_T.has_access
		, CALC_USER_T.can_view
		, CALC_USER_T.can_edit
		, CALC_USER_T.can_admin
        , CALC_USER_T.active
        , CALC_USER_T.does_meet_id_filters
        , CALC_USER_T.does_meet_non_id_filters
    FROM fetchmetrics.DOG_Calc_User_Access_Temp CALC_USER_T
    WHERE CALC_USER_T.GUID = a_guid
    ;
    
    IF a_debug = 1 THEN
        SELECT 'After get many user';
        SELECT * FROM tmp_Calc_User_Access_Calc_Image;
        SELECT COUNT(*) AS Count_Errors FROM tmp_Msg_Error_Calc_Image t_ERROR;
        SELECT * FROM tmp_Msg_Error_Calc_Image t_ERROR;
    END IF;
	
	CALL fetchmetrics.p_dog_clear_calc_user_access(
		a_guid
        , 0 -- a_debug
	);


    
    -- File Types
    IF v_has_filter_file_type_id = 1 THEN
		CALL fetchmetrics.p_core_split(a_guid, a_ids_file_type, ',', a_debug);

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

    IF v_has_filter_file_type_name = 1 THEN
		CALL fetchmetrics.p_core_split(a_guid, a_names_file_type, ',', a_debug);

        SET sql_mode = '';
		
		INSERT INTO tmp_Split_Name_Calc_Image (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CAST(SPLIT_T.substring AS DECIMAL(10,0)) AS as_int
		FROM fetchmetrics.CORE_Split_Temp SPLIT_T
		WHERE 
                SPLIT_T.GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') <> ''
		;
		
		CALL fetchmetrics.p_core_clear_split( a_guid );
	END IF;
    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_Image t_ERROR INNER JOIN fetchmetrics.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_Image t_SPLIT_ID
            LEFT JOIN fetchmetrics.CORE_File_Type FILE_TYPES ON t_SPLIT_ID.as_int = FILE_TYPES.id_file_type 
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
                OR  ISNULL(FILE_TYPES.id_file_type)
				OR  (
					FILE_TYPES.active = 0
					AND a_get_inactive_file_type = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error_Calc_Image (
				  id_type
		        , code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive File_Type IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT_ID.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split_Id_Calc_Image t_SPLIT_ID
			LEFT JOIN fetchmetrics.CORE_File_Type FILE_TYPES ON t_SPLIT_ID.as_int = FILE_TYPES.id_file_type
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
				OR  ISNULL(FILE_TYPES.id_file_type)
				OR  (
					FILE_TYPES.active = 0
					AND a_get_inactive_file_type = 0
				)
			;
        /* Don't error on names, hand signals, or notes not found
		ELSEIF EXISTS ()
        */
		ELSE
			INSERT INTO tmp_File_Type_Calc_Image (
				  id_file_type
                , does_meet_id_filters
                , does_meet_non_id_filters
			)
            WITH 
                  File_Type_Id_Filter AS (
                    SELECT FILE_TYPES.id_file_type
                    FROM tmp_Split_Id_Calc_Image t_SPLIT_ID
                    INNER JOIN fetchmetrics.CORE_File_Type FILE_TYPES ON t_SPLIT_ID.as_int = FILE_TYPES.id_file_type
                )
                , File_Type_Name_Filter AS (
                    SELECT FILE_TYPES.id_file_type
                    FROM tmp_Split_Name_Calc_Image t_SPLIT_NAME
                    INNER JOIN fetchmetrics.CORE_File_Type FILE_TYPES ON FILE_TYPES.name LIKE CONCAT('%', t_SPLIT_NAME.substring, '%')
                    WHERE 
                            t_SPLIT_NAME.substring IS NOT NULL
                        AND t_SPLIT_NAME.substring <> ''
                )
                , File_Type_Filters AS (
                    SELECT 
                          FILE_TYPES_COMBINED.id_file_type
                        , MAX(FILE_TYPES_COMBINED.does_meet_id_filter) AS does_meet_id_filter
                        , MAX(FILE_TYPES_COMBINED.does_meet_name_filter) AS does_meet_name_filter
                    FROM (
                        SELECT 
                              FILE_TYPES_ID_FILTER.id_file_type 
                            , 1 AS does_meet_id_filter
                            , 0 AS does_meet_name_filter
                        FROM File_Type_Id_Filter FILE_TYPES_ID_FILTER
                        UNION
                        SELECT 
                              FILE_TYPES_NAME_FILTER.id_file_type 
                            , 0 AS does_meet_id_filter
                            , 1 AS does_meet_name_filter
                        FROM File_Type_Name_Filter FILE_TYPES_NAME_FILTER
                    ) FILE_TYPES_COMBINED
                    GROUP BY FILE_TYPES_COMBINED.id_file_type
                )
            SELECT 
                  FILE_TYPES.id_file_type
                , CASE WHEN 
                        v_has_filter_file_type_id = 0 
                    OR  IFNULL(FILE_TYPES_FILTERS.does_meet_id_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_id_filters
                , CASE WHEN 
                        (
                            v_has_filter_file_type_name = 0
                    )
                    OR  IFNULL(FILE_TYPES_FILTERS.does_meet_name_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_non_id_filters
            FROM fetchmetrics.CORE_File_Type FILE_TYPES
            LEFT JOIN File_Type_Filters FILE_TYPES_FILTERS ON FILE_TYPES.id_file_type = FILE_TYPES_FILTERS.id_file_type
            WHERE 
                (
                        a_get_all_file_type = 1
                    OR  (
                            v_has_filter_file_type_id = 1
                        AND FILE_TYPES_FILTERS.does_meet_id_filter = 1
                    )
                    OR  (
                            v_has_filter_file_type_name = 1
                        AND FILE_TYPES_FILTERS.does_meet_name_filter = 1
                    )
                )
                AND (
                        a_get_inactive_file_type = 1
                    OR  FILE_TYPES.active = 1
                )
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split_Id_Calc_Image;
    DELETE FROM tmp_Split_Name_Calc_Image;


    -- Call Dog Calc
    IF NOT EXISTS(SELECT * FROM tmp_Msg_Error_Calc_Image t_ERROR INNER JOIN fetchmetrics.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 
                  a_guid -- a_guid
                , a_id_user -- a_id_user
                , a_get_all_dog -- a_get_all_dog
                , a_get_inactive_dog -- a_get_inactive_dog
                , a_ids_dog -- a_ids_dog
                , a_names_dog -- a_names_dog
                , a_get_all_user -- get_all_user
                , a_get_inactive_user -- get_inactive_user
                , a_ids_user -- ids_user
                , a_names_user -- a_names_user
                , a_emails_user -- a_emails_user
                , a_require_all_id_search_filters_met -- a_require_all_id_search_filters_met
                , 0 -- a_require_any_id_search_filters_met
                , a_require_all_non_id_search_filters_met -- a_require_all_non_id_search_filters_met
                , 0 -- a_require_any_non_id_search_filters_met
                , 0 -- a_show_errors
                , 0 -- a_debug
            ;
        END IF;
        
        CALL fetchmetrics.p_dog_calc_dog (
              a_guid -- a_guid
            , a_id_user -- a_id_user
            , a_get_all_dog -- a_get_all_dog
            , a_get_inactive_dog -- a_get_inactive_dog
            , a_ids_dog -- a_ids_dog
            , a_names_dog -- a_names_dog
            , a_get_all_user -- get_all_user
            , a_get_inactive_user -- get_inactive_user
            , a_ids_user -- ids_user
            , a_names_user -- a_names_user
            , a_emails_user -- a_emails_user
            , a_require_all_id_search_filters_met -- a_require_all_id_search_filters_met
            , 0 -- a_require_any_id_search_filters_met -- a_require_any_id_search_filters_met
            , a_require_all_non_id_search_filters_met -- a_require_all_non_id_search_filters_met
            , 0 -- a_require_any_non_id_search_filters_met -- a_require_any_non_id_search_filters_met
            , 0 -- a_show_errors
            , 0 -- a_debug
        );
        
        INSERT INTO tmp_Dog_Calc_Image (
              id_dog
            , active

            , does_meet_id_filters
            , does_meet_non_id_filters
        )
        SELECT
              DOG_T.id_dog
            , DOG_T.active

            , DOG_T.does_meet_id_filters
            , DOG_T.does_meet_non_id_filters
        FROM fetchmetrics.DOG_Dog_Temp DOG_T
        WHERE DOG_T.GUID = a_guid
        ;
        
        IF a_debug = 1 THEN
            SELECT * FROM tmp_Dog_Calc_Image;
        END IF;
    END IF;


    -- Images
    IF v_has_filter_image_id = 1 THEN
		CALL fetchmetrics.p_core_split(a_guid, a_ids_image, ',', a_debug);

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

    IF v_has_filter_image_name = 1 THEN
		CALL fetchmetrics.p_core_split(a_guid, a_names_image, ',', a_debug);

        SET sql_mode = '';
		
		INSERT INTO tmp_Split_Name_Calc_Image (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CAST(SPLIT_T.substring AS DECIMAL(10,0)) AS as_int
		FROM fetchmetrics.CORE_Split_Temp SPLIT_T
		WHERE 
                SPLIT_T.GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') <> ''
		;
		
		CALL fetchmetrics.p_core_clear_split( a_guid );
	END IF;
    
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_Image t_ERROR INNER JOIN fetchmetrics.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_Image t_SPLIT_ID
            LEFT JOIN fetchmetrics.DOG_Image IMAGES ON t_SPLIT_ID.as_int = IMAGES.id_image 
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
                OR  ISNULL(IMAGES.id_image)
				OR  (
					IMAGES.active = 0
					AND a_get_inactive_image = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error_Calc_Image (
				  id_type
		        , code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive Image IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT_ID.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split_Id_Calc_Image t_SPLIT_ID
			LEFT JOIN fetchmetrics.DOG_Image IMAGES ON t_SPLIT_ID.as_int = IMAGES.id_image
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
				OR  ISNULL(IMAGES.id_image)
				OR  (
					IMAGES.active = 0
					AND a_get_inactive_image = 0
				)
			;
        /* Don't error on names, hand signals, or notes not found
		ELSEIF EXISTS ()
        */
		ELSE
			INSERT INTO tmp_Image_Calc_Image (
				  id_image
                , id_file_type
                , exists_valid_link
                , id_user
                , does_meet_id_filters
                , does_meet_non_id_filters
			)
            WITH 
                  Image_Id_Filter AS (
                    SELECT IMAGES.id_image
                    FROM tmp_Split_Id_Calc_Image t_SPLIT_ID
                    INNER JOIN fetchmetrics.DOG_Image IMAGES ON t_SPLIT_ID.as_int = IMAGES.id_image
                )
                , Image_Name_Filter AS (
                    SELECT IMAGES.id_image
                    FROM tmp_Split_Name_Calc_Image t_SPLIT_NAME
                    INNER JOIN fetchmetrics.DOG_Image IMAGES ON IMAGES.name LIKE CONCAT('%', t_SPLIT_NAME.substring, '%')
                    WHERE 
                            t_SPLIT_NAME.substring IS NOT NULL
                        AND t_SPLIT_NAME.substring <> ''
                )
                , Image_Filters AS (
                    SELECT 
                          IMAGES_COMBINED.id_image
                        , MAX(IMAGES_COMBINED.does_meet_id_filter) AS does_meet_id_filter
                        , MAX(IMAGES_COMBINED.does_meet_name_filter) AS does_meet_name_filter
                    FROM (
                        SELECT 
                              IMAGES_ID_FILTER.id_image 
                            , 1 AS does_meet_id_filter
                            , 0 AS does_meet_name_filter
                        FROM Image_Id_Filter IMAGES_ID_FILTER
                        UNION
                        SELECT 
                              IMAGES_NAME_FILTER.id_image 
                            , 0 AS does_meet_id_filter
                            , 1 AS does_meet_name_filter
                        FROM Image_Name_Filter IMAGES_NAME_FILTER
                    ) IMAGES_COMBINED
                    GROUP BY IMAGES_COMBINED.id_image
                )
                , Image_Access AS (
                    SELECT 
                        IMAGES.id_image
                        , CASE WHEN 
                                v_is_super_user = 1
                            OR  (
                                    t_USER.id_user IS NOT NULL
                                AND IFNULL(ACCESS_LEVEL.priority, v_priority_access_level_none) <= v_priority_access_level_view
                            )
                        THEN 1 ELSE 0 END AS exists_valid_link
                        , ROW_NUMBER() OVER (
                            PARTITION BY IMAGES.id_image
                            ORDER BY 
                                  CASE WHEN 
                                        v_is_super_user = 1
                                    OR  (
                                            t_USER.id_user IS NOT NULL
                                        AND IFNULL(ACCESS_LEVEL.priority, v_priority_access_level_none) <= v_priority_access_level_view
                                    )
                                THEN 1 ELSE 0 END DESC
                                , t_USER.does_meet_id_filters DESC
                                , t_USER.does_meet_non_id_filters DESC
                        ) AS index_link_in_image
                        , t_USER.id_user
                    FROM fetchmetrics.DOG_Image IMAGES
                    LEFT JOIN fetchmetrics.DOG_Image_User_Link IMAGES_USER_LINK
                        ON  IMAGES.id_image = IMAGES_USER_LINK.id_image
                        AND (
                                (
                                    a_get_inactive_image = 1
                                AND a_get_inactive_user = 1
                            )
                            OR  IMAGES_USER_LINK.active = 1
                        )
                    LEFT JOIN tmp_Calc_User_Access_Calc_Image t_USER 
                        ON  IMAGES_USER_LINK.id_user = t_USER.id_user
                        AND (
                                a_get_inactive_user = 1
                            OR  t_USER.active = 1
                        )
                    LEFT JOIN fetchmetrics.DOG_Access_Level ACCESS_LEVEL 
                        ON  IMAGES_USER_LINK.id_access_level = ACCESS_LEVEL.id_access_level
                        AND ACCESS_LEVEL.active = 1
                )
            SELECT 
                  IMAGES.id_image
                , IMAGES.id_file_type
                , IFNULL(IMAGES_ACCESS.exists_valid_link, 0) AS exists_valid_link
                , IMAGES_ACCESS.id_user
                , CASE WHEN 
                        v_has_filter_image_id = 0 
                    OR  IFNULL(IMAGES_FILTERS.does_meet_id_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_id_filters
                , CASE WHEN 
                        (
                            v_has_filter_image_name = 0
                    )
                    OR  IFNULL(IMAGES_FILTERS.does_meet_name_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_non_id_filters
            FROM fetchmetrics.DOG_Image IMAGES
            INNER JOIN tmp_File_Type_Calc_Image t_FILE_TYPE ON IMAGES.id_file_type = t_FILE_TYPE.id_file_type
            LEFT JOIN tmp_Dog_Calc_Image t_DOG ON IMAGES.id_dog = t_DOG.id_dog
            LEFT JOIN Image_Filters IMAGES_FILTERS ON IMAGES.id_image = IMAGES_FILTERS.id_image
            LEFT JOIN Image_Access IMAGES_ACCESS 
                ON  IMAGES.id_image = IMAGES_ACCESS.id_image
                AND IMAGES_ACCESS.index_link_in_image = 1
            WHERE 
                (
                        a_get_all_image = 1
                    OR  (
                            v_has_filter_image_id = 1
                        AND IMAGES_FILTERS.does_meet_id_filter = 1
                    )
                    OR  (
                            v_has_filter_image_name = 1
                        AND IMAGES_FILTERS.does_meet_name_filter = 1
                    )
                )
                AND IFNULL(IMAGES_ACCESS.exists_valid_link, 0) = 1
                AND (
                        a_get_inactive_image = 1
                    OR  IMAGES.active = 1
                )
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split_Id_Calc_Image;
    DELETE FROM tmp_Split_Name_Calc_Image;

    IF a_debug = 1 THEN
        SELECT 'After get Images ';
        SELECT * FROM tmp_Image_Calc_Image;
    END IF;

    -- Filter records
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_Image t_ERROR INNER JOIN fetchmetrics.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_IMAGES
        FROM tmp_Image_Calc_Image t_IMAGES
        LEFT JOIN tmp_File_Type_Calc_Image t_FILE_TYPE ON t_IMAGES.id_file_type = t_FILE_TYPE.id_file_type
        LEFT JOIN tmp_Calc_User_Access_Calc_Image t_USER ON t_IMAGES.id_user = t_USER.id_user
        WHERE
                (
                    a_require_all_id_search_filters_met = 1
                AND (
                        t_IMAGES.does_meet_id_filters = 0
                    OR  IFNULL(t_FILE_TYPE.does_meet_id_filters, 0) = 0
                    OR  (
                            t_IMAGES.exists_valid_link = 0
                        AND IFNULL(t_USER.does_meet_id_filters, 0) = 0
                    )
                )
            )
            OR  (
                    a_require_all_non_id_search_filters_met = 1
                AND (
                        t_IMAGES.does_meet_non_id_filters = 0
                    OR  IFNULL(t_FILE_TYPE.does_meet_non_id_filters, 0) = 0
                    OR  (
                            t_IMAGES.exists_valid_link = 0
                        AND IFNULL(t_USER.does_meet_non_id_filters, 0) = 0
                    )
                )
            )
            OR  (
                a_require_any_id_search_filters_met = 1
                AND t_IMAGES.does_meet_id_filters = 0
                AND IFNULL(t_FILE_TYPE.does_meet_id_filters, 0) = 0
                AND (
                        t_IMAGES.exists_valid_link = 0
                    AND IFNULL(t_USER.does_meet_id_filters, 0) = 0
                )
            )
            OR  (
                a_require_any_non_id_search_filters_met = 1
                AND t_IMAGES.does_meet_non_id_filters = 0
                AND IFNULL(t_FILE_TYPE.does_meet_non_id_filters, 0) = 0
                AND (
                        t_IMAGES.exists_valid_link = 0
                    AND IFNULL(t_USER.does_meet_non_id_filters, 0) = 0
                )
            )
        ;
    END IF;

    IF a_debug = 1 THEN
        SELECT 'After filter Images';
        SELECT * FROM tmp_Image_Calc_Image;
    END IF;

    -- Calculated fields


    IF a_debug = 1 THEN
        SELECT 'Before non-permitted data deletion';
        SELECT * FROM tmp_Image_Calc_Image;
        SELECT * FROM tmp_Msg_Error_Calc_Image;
    END IF;
    
    IF EXISTS(SELECT * FROM tmp_Msg_Error_Calc_Image t_ERROR INNER JOIN fetchmetrics.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_Image_Calc_Image;
        END IF;

        DELETE FROM tmp_Image_Calc_Image;
    END IF;

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

    -- Outputs
	START TRANSACTION;
        -- Images
        INSERT INTO fetchmetrics.DOG_Image_Temp (
              guid
            , id_image
            , id_file_type
            , id_dog
            , path
            , name
            , active

            , does_meet_id_filters
            , does_meet_non_id_filters
        )
        SELECT 
              a_guid
            , t_IMAGES.id_image
            , IMAGES.id_file_type
            , IMAGES.id_dog
            , IMAGES.path
            , IMAGES.name
            , IMAGES.active

            , t_IMAGES.does_meet_id_filters
            , t_IMAGES.does_meet_non_id_filters
        FROM fetchmetrics.DOG_Image IMAGES
        INNER JOIN tmp_Image_Calc_Image t_IMAGES ON IMAGES.id_image = t_IMAGES.id_image
        ORDER BY IMAGES.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_Image t_ERROR
        INNER JOIN fetchmetrics.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_Image_Calc_Image;
    END IF;

    CALL fetchmetrics.p_dog_clear_calc_dog (
        a_guid -- a_guid
        , 0 -- debug
    );

    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Name_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Id_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Image_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Dog_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_File_Type_Calc_Image;
    DROP TEMPORARY TABLE IF EXISTS tmp_Calc_User_Access_Calc_Image;
    
    IF a_debug = 1 THEN
		CALL fetchmetrics.p_core_debug_timing_reporting ( v_time_start );
    END IF;
END //
DELIMITER ;


/*

SELECT *
FROM fetchmetrics.DOG_Image
;
SELECT *
FROM fetchmetrics.DOG_Image_User_Link
;

CALL fetchmetrics.p_dog_calc_image (
      'grope                               ' -- a_guid
	, 1 -- 'auth0|6582b95c895d09a70ba10fef',	-- a_id_user
    , 1                                     	-- a_get_all_file_type
	, 0                                     	-- a_get_inactive_file_type
	, ''                                    	-- a_ids_file_type
    , ''                                        -- a_names_file_type
    , 1                                     	-- a_get_all_dog
	, 0                                     	-- a_get_inactive_dog
	, ''                                    	-- a_ids_dog
	, ''                                    	-- a_names_dog
    , 1                                     	-- a_get_all_image
	, 0                                     	-- a_get_inactive_image
	, ''                                    	-- a_ids_image
    , ''                                        -- a_names_image
    , 1                                     	-- a_get_all_user
	, 0                                     	-- a_get_inactive_user
	, ''                                    	-- a_ids_user
    , ''                                        -- a_names_user
    , ''                                        -- a_emails_user
    , 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 fetchmetrics.DOG_Image_Temp
;
CALL fetchmetrics.p_dog_clear_calc_image (
	'grope                               ' -- a_guid
    , 1 -- debug
);


DELETE
FROM fetchmetrics.DOG_Image_Temp
;

*/
