 
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_calc_location;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_calc_location (
      IN a_guid BINARY(36)
    , IN a_id_user INT
    , IN a_get_all_location BIT
	, IN a_get_inactive_location BIT
	, IN a_ids_location TEXT
    , IN a_names_location 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_location_id BIT;
    DECLARE v_has_filter_location_name BIT;
    DECLARE v_id_access_level_view INT;
    DECLARE v_id_minimum INT;
    DECLARE v_id_permission_command_view INT;
    DECLARE v_id_type_error_bad_data INT;
    DECLARE v_id_type_error_no_permission INT;
    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_Location (
			  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_Location (
			  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_Location 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_Location;
    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_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_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_location := IFNULL(a_get_all_location, 0);
    SET a_get_inactive_location := IFNULL(a_get_inactive_location, 0);
    SET a_ids_location := TRIM(IFNULL(a_ids_location, ''));
    SET a_names_location := TRIM(IFNULL(a_names_location, ''));
    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_location
            , a_get_inactive_location
            , a_ids_location
            , a_names_location
            , 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_access_level_view
            , v_id_permission_command_view
            , v_priority_access_level_none
            , v_priority_access_level_view
            , v_time_start
        ;
    END IF;

    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Name_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Id_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error_Calc_Location;
    -- DROP TEMPORARY TABLE IF EXISTS tmp_Location_Link_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Location_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Calc_User_Access_Calc_Location;
    
	CREATE TEMPORARY TABLE tmp_Calc_User_Access_Calc_Location (
		  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_Location_Calc_Location (
		  id_location INT NOT NULL
        , id_location_parent INT
        , does_meet_id_filters BIT NOT NULL
        , does_meet_non_id_filters BIT NOT NULL
		, csv_id_locations_parent TEXT
    );
    
    /*
    CREATE TEMPORARY TABLE tmp_Location_Link_Calc_Location (
		  id_link INT NOT NULL
		, id_location_parent INT 
		, id_location_child INT
        , does_meet_id_filters BIT
        , does_meet_non_id_filters BIT
    );
    */

	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error_Calc_Location (
          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_Location (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Id_Calc_Location;
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Name_Calc_Location (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT
	);
    DELETE FROM tmp_Split_Name_Calc_Location;
    
    SET v_has_filter_location_id = CASE WHEN a_ids_location <> '' THEN 1 ELSE 0 END;
    SET v_has_filter_location_name = CASE WHEN a_names_location <> '' 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_id_permission_command_view -- 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_id_permission_command_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)
        , 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_Location t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error_Calc_Location (
			  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 Locations.'
		)
        ;
    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_id_permission_command_view -- 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
        , 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_id_permission_command_view -- ids_permission
        , v_id_access_level_view -- ids_access_level
        , 0 -- a_show_errors
        , 0 -- a_debug
    );
	
    INSERT INTO tmp_Calc_User_Access_Calc_Location (
        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 * FROM tmp_Calc_User_Access_Calc_Location;
    END IF;
	
	CALL fetchmetrics.p_dog_clear_calc_user_access (
		a_guid
        , 0 -- a_debug
	);

    -- Locations
    IF v_has_filter_location_id = 1 THEN
		CALL fetchmetrics.p_core_split(a_guid, a_ids_location, ',', a_debug);

        SET sql_mode = '';
		
		INSERT INTO tmp_Split_Id_Calc_Location (
			  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_location_name = 1 THEN
		CALL fetchmetrics.p_core_split(a_guid, a_names_location, ',', a_debug);

        SET sql_mode = '';
		
		INSERT INTO tmp_Split_Name_Calc_Location (
			  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_Location 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_Location t_SPLIT_ID
            LEFT JOIN fetchmetrics.DOG_Location LOCATIONS ON t_SPLIT_ID.as_int = LOCATIONS.id_location 
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
                OR  ISNULL(LOCATIONS.id_location)
				OR  (
					LOCATIONS.active = 0
					AND a_get_inactive_location = 0
				)
		) THEN
			INSERT INTO tmp_Msg_Error_Calc_Location (
				  id_type
		        , code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
                , v_code_type_error_bad_data
				, CONCAT('Invalid or inactive Location IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT_ID.substring SEPARATOR ', '), 'NULL'))
			FROM tmp_Split_Id_Calc_Location t_SPLIT_ID
			LEFT JOIN fetchmetrics.DOG_Location LOCATIONS ON t_SPLIT_ID.as_int = LOCATIONS.id_location
			WHERE 
				    ISNULL(t_SPLIT_ID.as_int) 
				OR  ISNULL(LOCATIONS.id_location)
				OR  (
					LOCATIONS.active = 0
					AND a_get_inactive_location = 0
				)
			;
        /* Don't error on names, hand signals, or notes not found
		ELSEIF EXISTS ()
        */
		ELSE
            IF a_debug = 1 THEN
                SELECT 'Location Filters';
                WITH 
                    Location_Id_Filter AS (
                        SELECT LOCATIONS.id_location
                        FROM tmp_Split_Id_Calc_Location t_SPLIT_ID
                        INNER JOIN fetchmetrics.DOG_Location LOCATIONS ON t_SPLIT_ID.as_int = LOCATIONS.id_location
                    )
                    , Location_Name_Filter AS (
                        SELECT LOCATIONS.id_location
                        FROM tmp_Split_Name_Calc_Location t_SPLIT_NAME
                        INNER JOIN fetchmetrics.DOG_Location LOCATIONS ON LOCATIONS.name LIKE CONCAT('%', t_SPLIT_NAME.substring, '%')
                        WHERE NULLIF(t_SPLIT_NAME.substring, '') IS NOT NULL
                    )
                    , Location_Filters AS (
                        SELECT 
                            LOCATIONS_COMBINED.id_location
                            , MAX(LOCATIONS_COMBINED.does_meet_id_filter) AS does_meet_id_filter
                            , MAX(LOCATIONS_COMBINED.does_meet_name_filter) AS does_meet_name_filter
                        FROM (
                            SELECT 
                                LOCATIONS_ID_FILTER.id_location 
                                , 1 AS does_meet_id_filter
                                , 0 AS does_meet_name_filter
                            FROM Location_Id_Filter LOCATIONS_ID_FILTER
                            UNION
                            SELECT 
                                LOCATIONS_NAME_FILTER.id_location 
                                , 0 AS does_meet_id_filter
                                , 1 AS does_meet_name_filter
                            FROM Location_Name_Filter LOCATIONS_NAME_FILTER
                        ) LOCATIONS_COMBINED
                        GROUP BY LOCATIONS_COMBINED.id_location
                    )
                SELECT 
                      LOCATIONS.id_location
                    , CASE WHEN 
                            v_has_filter_location_id = 0 
                        OR  IFNULL(LOCATIONS_FILTERS.does_meet_id_filter, 0) = 1
                    THEN 1 ELSE 0 END AS does_meet_id_filters
                    , CASE WHEN 
                            (
                                v_has_filter_location_name = 0
                        )
                        OR  IFNULL(LOCATIONS_FILTERS.does_meet_name_filter, 0) = 1
                    THEN 1 ELSE 0 END AS does_meet_non_id_filters
                FROM fetchmetrics.DOG_Location LOCATIONS
                LEFT JOIN Location_Filters LOCATIONS_FILTERS ON LOCATIONS.id_location = LOCATIONS_FILTERS.id_location
                LEFT JOIN fetchmetrics.DOG_Location_User_Link LOCATION_USER_LINK 
                    ON  LOCATIONS.id_location = LOCATION_USER_LINK.id_location
                    AND (
                            (
                                a_get_inactive_location = 1
                            AND a_get_inactive_user = 1
                        )
                        OR  LOCATION_USER_LINK.active = 1
                    )
                LEFT JOIN tmp_Calc_User_Access_Calc_Location t_USER 
                    ON  LOCATION_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  LOCATION_USER_LINK.id_access_level = ACCESS_LEVEL.id_access_level
                    AND ACCESS_LEVEL.active = 1
                WHERE 
                    (
                            a_get_all_location = 1
                        OR  (
                                v_has_filter_location_id = 1
                            AND LOCATIONS_FILTERS.does_meet_id_filter = 1
                        )
                        OR  (
                                v_has_filter_location_name = 1
                            AND LOCATIONS_FILTERS.does_meet_name_filter = 1
                        )
                    )
                    AND (
                            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
                        )
                    )
                    AND (
                            a_get_inactive_location = 1
                        OR  LOCATIONS.active = 1
                    )
                ;
            END IF;
			INSERT INTO tmp_Location_Calc_Location (
				  id_location
                , id_location_parent
                , does_meet_id_filters
                , does_meet_non_id_filters
			)
            WITH 
                  Location_Id_Filter AS (
                    SELECT LOCATIONS.id_location
                    FROM tmp_Split_Id_Calc_Location t_SPLIT_ID
                    INNER JOIN fetchmetrics.DOG_Location LOCATIONS ON t_SPLIT_ID.as_int = LOCATIONS.id_location
                )
                , Location_Name_Filter AS (
                    SELECT LOCATIONS.id_location
                    FROM tmp_Split_Name_Calc_Location t_SPLIT_NAME
                    INNER JOIN fetchmetrics.DOG_Location LOCATIONS ON LOCATIONS.name LIKE CONCAT('%', t_SPLIT_NAME.substring, '%')
                    WHERE 
                            t_SPLIT_NAME.substring IS NOT NULL
                        AND t_SPLIT_NAME.substring <> ''
                )
                , Location_Filters AS (
                    SELECT 
                          LOCATIONS_COMBINED.id_location
                        , MAX(LOCATIONS_COMBINED.does_meet_id_filter) AS does_meet_id_filter
                        , MAX(LOCATIONS_COMBINED.does_meet_name_filter) AS does_meet_name_filter
                    FROM (
                        SELECT 
                              LOCATIONS_ID_FILTER.id_location 
                            , 1 AS does_meet_id_filter
                            , 0 AS does_meet_name_filter
                        FROM Location_Id_Filter LOCATIONS_ID_FILTER
                        UNION
                        SELECT 
                              LOCATIONS_NAME_FILTER.id_location 
                            , 0 AS does_meet_id_filter
                            , 1 AS does_meet_name_filter
                        FROM Location_Name_Filter LOCATIONS_NAME_FILTER
                    ) LOCATIONS_COMBINED
                    GROUP BY LOCATIONS_COMBINED.id_location
                )
            SELECT 
                  LOCATIONS.id_location
                , LOCATIONS.id_location_parent
                , CASE WHEN 
                        v_has_filter_location_id = 0 
                    OR  IFNULL(LOCATIONS_FILTERS.does_meet_id_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_id_filters
                , CASE WHEN 
                        (
                            v_has_filter_location_name = 0
                    )
                    OR  IFNULL(LOCATIONS_FILTERS.does_meet_name_filter, 0) = 1
                THEN 1 ELSE 0 END AS does_meet_non_id_filters
            FROM fetchmetrics.DOG_Location LOCATIONS
            LEFT JOIN Location_Filters LOCATIONS_FILTERS ON LOCATIONS.id_location = LOCATIONS_FILTERS.id_location
            LEFT JOIN fetchmetrics.DOG_Location_User_Link LOCATION_USER_LINK 
                ON  LOCATIONS.id_location = LOCATION_USER_LINK.id_location
                AND (
                        (
                            a_get_inactive_location = 1
                        AND a_get_inactive_user = 1
                    )
                    OR  LOCATION_USER_LINK.active = 1
                )
            LEFT JOIN tmp_Calc_User_Access_Calc_Location t_USER 
                ON  LOCATION_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  LOCATION_USER_LINK.id_access_level = ACCESS_LEVEL.id_access_level
                AND ACCESS_LEVEL.active = 1
            WHERE 
                (
                        a_get_all_location = 1
                    OR  (
                            v_has_filter_location_id = 1
                        AND LOCATIONS_FILTERS.does_meet_id_filter = 1
                    )
                    OR  (
                            v_has_filter_location_name = 1
                        AND LOCATIONS_FILTERS.does_meet_name_filter = 1
                    )
                )
                AND (
                        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
                    )
                )
                AND (
                        a_get_inactive_location = 1
                    OR  LOCATIONS.active = 1
                )
			;
		END IF;
	END IF;
    
    DELETE FROM tmp_Split_Id_Calc_Location;
    DELETE FROM tmp_Split_Name_Calc_Location;

    IF a_debug = 1 THEN
        SELECT 'After get Locations ';
        SELECT * FROM tmp_Location_Calc_Location;
    END IF;

    -- Filter records
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_Location 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
        WITH 
              Location_Access AS (
                SELECT
                    LOCATIONS.id_location
                    , 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 can_user_access_location
                    , ROW_NUMBER() OVER (
                        PARTITION BY LOCATIONS.id_location 
                        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
                    ) AS index_link_in_location
                    , t_USER.does_meet_id_filters AS does_user_meet_id_filters
                    , t_USER.does_meet_non_id_filters AS does_user_meet_non_id_filters
                FROM fetchmetrics.DOG_Location LOCATIONS
                LEFT JOIN fetchmetrics.DOG_Location_User_Link LOCATION_USER_LINK
                    ON  LOCATIONS.id_location = LOCATION_USER_LINK.id_location
                    AND (
                            (
                                a_get_inactive_location = 1
                            AND a_get_inactive_user = 1
                        )
                        OR  LOCATION_USER_LINK.active = 1
                    )
                LEFT JOIN tmp_Calc_User_Access_Calc_Location t_USER 
                    ON  LOCATION_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  LOCATION_USER_LINK.id_access_level = ACCESS_LEVEL.id_access_level
                    AND ACCESS_LEVEL.active = 1
            )
        DELETE t_LOCATIONS
        FROM tmp_Location_Calc_Location t_LOCATIONS
        LEFT JOIN Location_Access LOCATION_ACCESS ON t_LOCATIONS.id_location = LOCATION_ACCESS.id_location
        WHERE
                (
                    a_require_all_id_search_filters_met = 1
                AND (
                        t_LOCATIONS.does_meet_id_filters = 0
                    OR  (
                            IFNULL(LOCATION_ACCESS.can_user_access_location, 0) = 0
                        AND IFNULL(LOCATION_ACCESS.does_user_meet_non_id_filters, 0) = 0
                    )
                )
            )
            OR  (
                    a_require_all_non_id_search_filters_met = 1
                AND (
                        t_LOCATIONS.does_meet_non_id_filters = 0
                    OR  (
                            IFNULL(LOCATION_ACCESS.can_user_access_location, 0) = 0
                        AND IFNULL(LOCATION_ACCESS.does_user_meet_non_id_filters, 0) = 0
                    )
                )
            )
            OR  (
                    a_require_any_id_search_filters_met = 1
                AND t_LOCATIONS.does_meet_id_filters = 0
                AND (
                        IFNULL(LOCATION_ACCESS.can_user_access_location, 0) = 0
                    AND IFNULL(LOCATION_ACCESS.does_user_meet_non_id_filters, 0) = 0
                )
            )
            OR  (
                    a_require_any_non_id_search_filters_met = 1
                AND t_LOCATIONS.does_meet_non_id_filters = 0
                AND (
                        IFNULL(LOCATION_ACCESS.can_user_access_location, 0) = 0
                    AND IFNULL(LOCATION_ACCESS.does_user_meet_non_id_filters, 0) = 0
                )
            )
        ;
    END IF;

    IF a_debug = 1 THEN
        SELECT 'After filter Locations';
        SELECT * FROM tmp_Location_Calc_Location;
    END IF;

    -- Calculated fields
    /*
    -- Parent Location Ids
    WITH Location_Parent AS (
        SELECT
              LOCATIONS.id_location
            , GROUP_CONCAT(LOCATION_LINK.id_location_parent, ',') AS csv_id_locations_parent
        FROM fetchmetrics.DOG_Location LOCATIONS
        INNER JOIN DOG_Location_Link LOCATION_LINK ON LOCATIONS.id_location = LOCATION_LINK.id_location_child
        WHERE 
                a_get_inactive_location = 1
            OR  LOCATION_LINK.active = 1
        GROUP BY LOCATIONS.id_location
    )
	UPDATE tmp_Location_Calc_Location t_LOCATIONS
    INNER JOIN Location_Parent LOCATIONS_PARENT ON t_LOCATIONS.id_location = LOCATIONS_PARENT.id_location
	SET
		  t_LOCATIONS.csv_id_locations_parent = LOCATIONS_PARENT.csv_id_locations_parent
	;

    IF a_debug = 1 THEN
        SELECT 'After generate calculated fields Locations';
        SELECT * FROM tmp_Location_Calc_Location;
    END IF;
    */


    IF a_debug = 1 THEN
        SELECT 'Before non-permitted data deletion';
        SELECT * FROM tmp_Location_Calc_Location;
        SELECT * FROM tmp_Msg_Error_Calc_Location;
    END IF;
    
    IF EXISTS(SELECT * FROM tmp_Msg_Error_Calc_Location 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_Location_Calc_Location;
        END IF;

        DELETE FROM tmp_Location_Calc_Location;
    END IF;

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

    -- Outputs
	START TRANSACTION;
        -- Locations
        INSERT INTO fetchmetrics.DOG_Location_Temp (
              guid
            , id_location
            , id_location_parent
            , code
            , name
            , active

            , csv_id_locations_parent

            , does_meet_id_filters
            , does_meet_non_id_filters
        )
        SELECT 
              a_guid
            , t_LOCATIONS.id_location
            , t_LOCATIONS.id_location_parent
            , LOCATIONS.code
            , LOCATIONS.name
            , LOCATIONS.active

            , t_LOCATIONS.csv_id_locations_parent

            , t_LOCATIONS.does_meet_id_filters
            , t_LOCATIONS.does_meet_non_id_filters
        FROM fetchmetrics.DOG_Location LOCATIONS
        INNER JOIN tmp_Location_Calc_Location t_LOCATIONS ON LOCATIONS.id_location = t_LOCATIONS.id_location
        ORDER BY LOCATIONS.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_Location 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_Location_Calc_Location;
    END IF;
    
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Name_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Split_Id_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Msg_Error_Calc_Location;
    -- DROP TEMPORARY TABLE IF EXISTS tmp_Location_Link_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Location_Calc_Location;
    DROP TEMPORARY TABLE IF EXISTS tmp_Calc_User_Access_Calc_Location;
    
    IF a_debug = 1 THEN
		CALL fetchmetrics.p_core_debug_timing_reporting ( v_time_start );
    END IF;
END //
DELIMITER ;


/*


CALL fetchmetrics.p_dog_calc_location (
      'grops                               ' -- a_guid
	, 1 -- 'auth0|6582b95c895d09a70ba10fef',	-- a_id_user
    , 1                                     	-- a_get_all_location
	, 0                                     	-- a_get_inactive_location
	, ''                                    	-- a_ids_location
    , ''                                        -- a_names_location
    , 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
);

CALL fetchmetrics.p_dog_calc_location (
      'grops                               ' -- a_guid
	, 1 -- 'auth0|6582b95c895d09a70ba10fef',	-- a_id_user
    , 1                                     	-- a_get_all_location
	, 0                                     	-- a_get_inactive_location
	, ''                                    	-- a_ids_location
    , 'pat,point'                                        -- a_names_location
    , 1                                     	-- a_get_all_user
	, 0                                     	-- a_get_inactive_user
	, ''                                    	-- a_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
    , 1                                         -- a_require_any_non_id_search_filters_met
    , 1                                         -- a_show_errors
    , 0                                     	-- a_debug
);
SELECT *
FROM fetchmetrics.DOG_Location_Temp
;
CALL fetchmetrics.p_dog_clear_calc_location (
	'grops                               ' -- a_guid
    , 1 -- debug
);


DELETE
FROM fetchmetrics.DOG_Location_Temp
;

*/
