
-- Clear previous proc
DROP PROCEDURE IF EXISTS p_dog_user_eval;
DROP PROCEDURE IF EXISTS p_dog_calc_user;

DELIMITER //
CREATE PROCEDURE p_dog_calc_user (
	  IN a_guid BINARY(36)
    , IN a_ids_user TEXT
    , IN a_get_inactive_user BIT
    , IN a_ids_permission TEXT
    , IN a_ids_access_level TEXT
    , IN a_show_errors BIT
    , IN a_debug BIT
)
BEGIN
    DECLARE v_code_type_error_bad_data VARCHAR(200);
    DECLARE v_code_type_error_no_permission VARCHAR(200);
    DECLARE v_has_filter_permission BIT;
    DECLARE v_has_filter_user BIT;
    DECLARE v_has_filter_access_level BIT;
    DECLARE v_id_access_level INT;
    DECLARE v_id_access_level_view INT;
    DECLARE v_id_permission INT;
    DECLARE v_id_permission_required INT;
    DECLARE v_id_type_error_bad_data INT;
	DECLARE v_ids_row_delete VARCHAR(500);
    DECLARE v_priority_access_level_view INT;
    DECLARE v_priority_access_level_edit INT;
    DECLARE v_priority_access_level_admin INT;
    DECLARE v_priority_access_level 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_User (
			  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT NULL
			, code VARCHAR(100) NOT NULL
			, msg TEXT NOT NULL
		);

        INSERT INTO tmp_Msg_Error_Calc_User (
			  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_User 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_User;
    END;
    
    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_code_type_error_bad_data := 'BAD_DATA';
    SET v_id_type_error_bad_data := (SELECT id_type FROM parts.CORE_Msg_Error_Type WHERE code = v_code_type_error_bad_data LIMIT 1);
    
    SET v_code_type_error_no_permission := (SELECT code FROM parts.CORE_Msg_Error_Type WHERE id_type = 2);
    
    CALL parts.p_validate_guid ( a_guid );
    SET a_ids_user := TRIM(IFNULL(a_ids_user, ''));
    SET a_get_inactive_user := IFNULL(a_get_inactive_user, 0);
    SET a_ids_permission := TRIM(IFNULL(a_ids_permission, ''));
    SET a_ids_access_level := TRIM(IFNULL(a_ids_access_level, ''));
    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_ids_user
            , a_get_inactive_user
            , a_ids_permission
            , a_ids_access_level
            , a_show_errors
            , a_debug
		;
    END IF;
    
	-- Clear previous proc results
	DROP TABLE IF EXISTS tmp_Split_Calc_User;
	DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User;
	DROP TABLE IF EXISTS tmp_User_Calc_User;
	DROP TABLE IF EXISTS tmp_Calc_User;
    
    -- Permanent Table
	CREATE TEMPORARY TABLE tmp_Calc_User (
		  id_row INT PRIMARY KEY AUTO_INCREMENT NOT NULL
		, id_user INT
		, id_permission_required INT NOT NULL
		, priority_access_level_required INT NOT NULL
        , is_super_user BIT
		, priority_access_level_user INT
		, can_view BIT
		, can_edit BIT
		, can_admin BIT
	);

	CREATE TEMPORARY TABLE tmp_User_Calc_User (
		  id_user INT NOT NULL
        , is_super_user BIT NOT NULL
        , priority_access_level INT NOT NULL
	);
    
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error_Calc_User (
		  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT NULL
        , code VARCHAR(100) NOT NULL
        , msg TEXT NOT NULL
	);
    
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Split_Calc_User (
		  substring VARCHAR(4000) NOT NULL
        , as_int INT NULL
	);
    DELETE FROM tmp_Split_Calc_User;
		
    SET v_has_filter_user = CASE WHEN a_ids_user = '' THEN 0 ELSE 1 END;
    SET v_has_filter_permission = CASE WHEN a_ids_permission = '' THEN 0 ELSE 1 END;
    SET v_has_filter_access_level = CASE WHEN a_ids_access_level = '' THEN 0 ELSE 1 END;
    SET v_id_access_level_view = (SELECT id_access_level FROM parts.DOG_Access_Level WHERE code = 'VIEW' LIMIT 1);
    SET v_priority_access_level_view = (SELECT priority FROM parts.DOG_Access_Level WHERE id_access_level = v_id_access_level_view);
    SET v_priority_access_level_edit = (SELECT priority FROM parts.DOG_Access_Level WHERE code = 'EDIT' LIMIT 1);
    SET v_priority_access_level_admin = (SELECT priority FROM parts.DOG_Access_Level WHERE code = 'ADMIN' LIMIT 1);
    
    IF a_debug = 1 THEN
		SELECT 
			  v_priority_access_level_view
			, v_priority_access_level_edit
			, v_priority_access_level_admin
		;
    END IF;
    
    # Access levels
	IF v_has_filter_access_level = 1 THEN
        IF a_debug = 1 THEN
            SELECT
                  'p_core_split'
                , a_guid
                , a_ids_access_level
                , ','
                , a_debug
            ;
        END IF;

		CALL parts.p_core_clear_split( a_guid );
		CALL parts.p_core_split(a_guid, a_ids_access_level, ',', a_debug);
		
        DELETE FROM tmp_Split_Calc_User;
		INSERT INTO tmp_Split_Calc_User (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CONVERT(SPLIT_T.substring, DECIMAL(10,0)) -- AS as_int
		FROM parts.CORE_Split_Temp SPLIT_T
		WHERE
			    GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') != ''
		;

        IF a_debug = 1 THEN
            SELECT 'Access Levels split', a_ids_access_level;
            SELECT *
            FROM tmp_Split_Calc_User;
        END IF;
		
		CALL parts.p_core_clear_split( a_guid );
		
		# Invalid IDs
		IF EXISTS (
			SELECT t_SPLIT.substring 
			FROM tmp_Split_Calc_User t_SPLIT
			LEFT JOIN parts.DOG_Access_Level ACCESS_LEVEL ON t_SPLIT.as_int = ACCESS_LEVEL.id_access_level
			WHERE 
				    ISNULL(t_SPLIT.as_int)
				OR  ISNULL(ACCESS_LEVEL.id_access_level)
				OR  ACCESS_LEVEL.active = 0
		) THEN
			INSERT INTO tmp_Msg_Error_Calc_User (
				  id_type
				, code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
				, v_code_type_error_bad_data
				, CONCAT('Invalid or inactive access level IDs: ', GROUP_CONCAT(t_SPLIT.substring SEPARATOR ','))
			FROM tmp_Split_Calc_User t_SPLIT 
			LEFT JOIN parts.DOG_Access_Level ACCESS_LEVEL ON t_SPLIT.as_int = ACCESS_LEVEL.id_access_level
			WHERE 
				    ISNULL(t_SPLIT.as_int)
				OR  ISNULL(ACCESS_LEVEL.id_access_level)
				OR  ACCESS_LEVEL.active = 0
			;

            SET v_has_filter_access_level = 0;
        ELSE
            SET v_id_access_level := (
                SELECT ACCESS_LEVEL.id_access_level 
                FROM tmp_Split_Calc_User t_SPLIT
                INNER JOIN parts.DOG_Access_Level ACCESS_LEVEL 
                    ON  t_SPLIT.as_int = ACCESS_LEVEL.id_access_level
                    AND ACCESS_LEVEL.active = 1
                ORDER BY ACCESS_LEVEL.priority ASC 
                LIMIT 1
            );
		END IF;
	END IF;
	DELETE FROM tmp_Split_Calc_User;

    IF ISNULL(v_id_access_level) THEN
        SET v_id_access_level = v_id_access_level_view;
    END IF;

    SET v_priority_access_level := (SELECT priority FROM parts.DOG_Access_Level WHERE id_access_level = v_id_access_level LIMIT 1);
    
    -- Permission IDs
	IF v_has_filter_permission = 1 THEN
		CALL parts.p_core_clear_split( a_guid );
		CALL parts.p_core_split(a_guid, a_ids_permission, ',', a_debug);
		
	    DELETE FROM tmp_Split_Calc_User;
		INSERT INTO tmp_Split_Calc_User (
			  substring
			, as_int
		)
		SELECT 
			  SPLIT_T.substring
			, CONVERT(SPLIT_T.substring, DECIMAL(10,0)) AS as_int
		FROM parts.CORE_Split_Temp SPLIT_T
		WHERE 
			    GUID = a_guid
			AND IFNULL(SPLIT_T.substring, '') != ''
		;

        IF a_debug = 1 THEN
            SELECT 'Permissions split', a_ids_permission;
            SELECT *
            FROM tmp_Split_Calc_User;
        END IF;
		
		CALL parts.p_core_clear_split( a_guid );
		
		# Invalid or inactive
		IF EXISTS (SELECT PERMISSION.id_permission FROM tmp_Split_Calc_User t_SPLIT LEFT JOIN parts.DOG_Permission PERMISSION ON t_SPLIT.as_int = PERMISSION.id_permission WHERE ISNULL(t_SPLIT.as_int) OR ISNULL(PERMISSION.id_permission) OR PERMISSION.active = 0) THEN
			INSERT INTO tmp_Msg_Error_Calc_User (
				  id_type
				, code
				, msg
			)
			SELECT
				  v_id_type_error_bad_data
				, v_code_type_error_bad_data
				, CONCAT('Invalid or inactive permission IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ','), 'NULL'))
			FROM tmp_Split_Calc_User t_SPLIT
			LEFT JOIN parts.DOG_Permission PERMISSION ON t_SPLIT.as_int = PERMISSION.id_permission 
			WHERE 
				    ISNULL(t_SPLIT.as_int)
				OR  ISNULL(PERMISSION.id_permission)
				OR  PERMISSION.active = 0
			;
		ELSE 
			SET v_id_permission_required := (
				SELECT PERMISSION.id_permission
				FROM tmp_Split_Calc_User t_SPLIT
				INNER JOIN parts.DOG_Permission PERMISSION ON t_SPLIT.as_int = PERMISSION.id_permission
                INNER JOIN parts.DOG_Access_Level ACCESS_LEVEL ON PERMISSION.id_access_level_required = ACCESS_LEVEL.id_access_level
				ORDER BY ACCESS_LEVEL.priority ASC
				LIMIT 1
			);
		END IF;
	END IF;
    DELETE FROM tmp_Split_Calc_User;
    
	# Users
	CALL parts.p_core_clear_split( a_guid );
	CALL parts.p_core_split(a_guid, a_ids_user, ',', a_debug);
	
	DELETE FROM tmp_Split_Calc_User;
	INSERT INTO tmp_Split_Calc_User (
		  substring
		, as_int
	)
	SELECT 
		  substring
		, CONVERT(substring, DECIMAL(10,0)) AS as_int
	FROM parts.CORE_Split_Temp
	WHERE
		    GUID = a_guid
		AND NOT ISNULL(substring)
		AND substring != ''
	;

    IF a_debug = 1 THEN
        SELECT 'Users split', a_ids_user;
        SELECT *
        FROM tmp_Split_Calc_User;
    END IF;
	
	CALL parts.p_core_clear_split( a_guid );
    
    IF a_debug = 1 THEN
        SELECT v_id_permission_required, v_id_access_level, v_priority_access_level;
        SELECT * FROM tmp_User_Calc_User;
        SELECT * FROM tmp_Msg_Error_Calc_User;
    END IF;
	
	# Invalid or inactive
	IF EXISTS (
        SELECT USER.id_user 
        FROM tmp_Split_Calc_User t_SPLIT 
        LEFT JOIN parts.DOG_User USER ON t_SPLIT.as_int = USER.id_user 
        WHERE 
                ISNULL(t_SPLIT.as_int) 
            OR  ISNULL(USER.id_user) 
            OR  (
                    a_get_inactive_user = 0 
                AND USER.active = 0
            )
        ) 
    THEN
		INSERT INTO tmp_Msg_Error_Calc_User (
			  id_type
			, code
			, msg
		)
		SELECT
			  v_id_type_error_bad_data
			, v_code_type_error_bad_data
		    , CONCAT('Invalid or inactive user IDs: ', IFNULL(GROUP_CONCAT(t_SPLIT.substring SEPARATOR ','), 'NULL'))
		FROM tmp_Split_Calc_User t_SPLIT
		LEFT JOIN parts.DOG_User USER ON t_SPLIT.as_int = USER.id_user 
		WHERE 
			    ISNULL(t_SPLIT.as_int) 
			OR  ISNULL(USER.id_user)
			OR  (
				    a_get_inactive_user = 0
                AND USER.active = 0
			)
		;
	ELSE
		IF NOT EXISTS (SELECT * FROM tmp_Split_Calc_User) THEN
			INSERT INTO tmp_Split_Calc_User ( substring, as_int )
			VALUES ( '', NULL );
		END IF;
		
        INSERT INTO tmp_User_Calc_User (
			  id_user
            , is_super_user
            , priority_access_level
		)
        SELECT
			  USER.id_user
            , IFNULL(USER.is_super_user, 0) AS is_super_user
            , IFNULL(MIN(ACCESS_LEVEL.priority), v_priority_access_level_view) AS priority_access_level
		FROM tmp_Split_Calc_User t_SPLIT
        INNER JOIN parts.DOG_User USER ON t_SPLIT.as_int = USER.id_user
		LEFT JOIN parts.DOG_User_Role_Link USER_ROLE_LINK
			ON  USER.id_user = USER_ROLE_LINK.id_user
			AND USER_ROLE_LINK.active
		LEFT JOIN parts.DOG_Role_Permission_Link ROLE_PERMISSION_LINK
			ON  USER_ROLE_LINK.id_role = ROLE_PERMISSION_LINK.id_role
			AND ROLE_PERMISSION_LINK.active
		LEFT JOIN parts.DOG_Access_Level ACCESS_LEVEL
			ON  ROLE_PERMISSION_LINK.id_access_level = ACCESS_LEVEL.id_access_level
			AND ACCESS_LEVEL.active
		GROUP BY USER.id_user
        ;
        			
		INSERT INTO tmp_Calc_User (
			  id_user
			, id_permission_required
			, priority_access_level_required
			, priority_access_level_user
            , is_super_user
		)
		SELECT 
			  t_USER.id_user
			, v_id_permission_required
			, v_priority_access_level AS priority_access_level_required
			, t_USER.is_super_user AS is_super_user
			, t_USER.priority_access_level AS priority_access_level_user
		FROM tmp_User_Calc_User t_USER
        ;
	
		# SET v_has_filter_user = EXISTS ( SELECT * FROM tmp_User_Calc_User LIMIT 1 );
	END IF;    
    DELETE FROM tmp_Split_Calc_User;
    
    -- Calculated fields
	UPDATE tmp_Calc_User t_CALC_USER
	SET
		  t_CALC_USER.can_view = t_CALC_USER.is_super_user = 1 OR (t_CALC_USER.priority_access_level_user <= v_priority_access_level_view AND t_CALC_USER.priority_access_level_user <= t_CALC_USER.priority_access_level_required)
		, t_CALC_USER.can_edit = t_CALC_USER.is_super_user = 1 OR (t_CALC_USER.priority_access_level_user <= v_priority_access_level_edit AND t_CALC_USER.priority_access_level_user <= t_CALC_USER.priority_access_level_required)
		, t_CALC_USER.can_admin = t_CALC_USER.is_super_user = 1 OR (t_CALC_USER.priority_access_level_user <= v_priority_access_level_admin AND t_CALC_USER.priority_access_level_user <= t_CALC_USER.priority_access_level_required)
	;
    
    -- Export data to staging table
    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error_Calc_User) THEN
        START TRANSACTION;
			INSERT INTO parts.DOG_Calc_User_Temp (
				  guid
				, id_user
				, id_permission_required
				, priority_access_level_required
				, is_super_user
				, priority_access_level_user
                , has_access
				, can_view
				, can_edit
				, can_admin
			)
			SELECT
				  a_guid
				, t_CALC_USER.id_user
				, t_CALC_USER.id_permission_required
				, t_CALC_USER.priority_access_level_required
				, t_CALC_USER.is_super_user
				, t_CALC_USER.priority_access_level_user
                , CASE WHEN t_CALC_USER.priority_access_level_user <= t_CALC_USER.priority_access_level_required THEN 1 ELSE 0 END AS has_access
				, t_CALC_USER.can_view
				, t_CALC_USER.can_edit
				, t_CALC_USER.can_admin
			FROM tmp_Calc_User t_CALC_USER
			;
		COMMIT;
    END IF;
    
    -- 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_User 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 THEN
		SELECT * FROM tmp_Msg_Error_Calc_User;
		SELECT * FROM tmp_Calc_User;
        SELECT * FROM tmp_User_Calc_User;
		SELECT * FROM parts.DOG_Calc_User_Temp WHERE GUID = a_guid;
		CALL parts.p_dog_clear_calc_user ( a_guid, a_debug );
    END IF;
    
    -- Clean up
	DROP TABLE IF EXISTS tmp_Split_Calc_User;
	DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User;
	DROP TABLE IF EXISTS tmp_User_Calc_User;
	DROP TABLE IF EXISTS tmp_Calc_User;
    
    IF a_debug = 1 THEN
        CALL parts.p_debug_timing_reporting( v_time_start );
    END IF;
END //
DELIMITER ;

/*

CALL parts.p_dog_calc_user (
	'chips                               '  -- a_guid
	, 1                                     -- a_ids_user
	, 0                                     -- a_get_inactive_user
	, '2'                                   -- a_ids_permission
	, '1'                                   -- a_ids_access_level
    , 0                                     -- a_show_errors
    , 0                                     -- a_debug
);
CALL parts.p_dog_calc_user (
	'chips                               '  -- a_guid
	, 1                                     -- a_ids_user
	, 0                                     -- a_get_inactive_user
	, '2'                                   -- a_ids_permission
	, '1'                                   -- a_ids_access_level
    , 0                                     -- a_show_errors
    , 0                                     -- a_debug
);
SELECT * FROM parts.DOG_Calc_User_Temp WHERE GUID = 'chips                               ';
DELETE FROM parts.DOG_Calc_User_Temp WHERE GUID = 'chips                               ';

*/

        
-- SELECT * FROM parts.DOG_Calc_User_Temp;
SELECT * FROM parts.DOG_Calc_User_Temp WHERE GUID = 'chips                               ';
CALL parts.p_dog_clear_calc_user ( 'chips                               ', 0 );
-- SELECT * FROM parts.DOG_Calc_User_Temp;
DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User;

CALL parts.p_dog_calc_user(
      'chips                               '-- a_guid
    , '1'                                     -- a_ids_user
    , 0                                     -- a_get_inactive_user
    , '8'                                   -- a_ids_permission
    , '1'                                   -- a_ids_access_level
    , 1                                     -- a_show_errors
    , 0                                     -- a_debug
);
SELECT * FROM parts.DOG_Calc_User_Temp WHERE GUID = 'chips                               ';
CALL parts.p_dog_clear_calc_user ( 'chips                               ', 0 );
DROP TABLE IF EXISTS tmp_Msg_Error_Calc_User;


