
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_save_button_icon;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_save_button_icon (
    IN a_comment VARCHAR(500),
	IN a_guid BINARY(36),
    IN a_id_user INT,
    IN a_debug BIT
)
BEGIN
    DECLARE v_can_admin BIT;
    DECLARE v_can_create BIT;
	DECLARE v_code_type_error_bad_data VARCHAR(100);
    DECLARE v_id_access_level_edit INT;
    DECLARE v_id_change_set INT;
    DECLARE v_id_permission_dog_new INT;
    DECLARE v_id_type_error_bad_data 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 (
			  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
			, id_type INT
			, code VARCHAR(250)
			, msg TEXT NOT NULL
		);

        INSERT INTO tmp_Msg_Error (
			  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 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;
    END;
    
    SET SESSION group_concat_max_len=15000;

    SET v_time_start := CURRENT_TIMESTAMP(6);
    SET v_code_type_error_bad_data := 'BAD_DATA';
    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_permission_dog_new := (SELECT PERMISSION.id_permission FROM fetchmetrics.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_CREATE' LIMIT 1);
    SET v_id_access_level_edit := (SELECT ACCESS_LEVEL.id_access_level FROM fetchmetrics.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'EDIT' LIMIT 1);
    
    CALL fetchmetrics.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Button_Icon_Copy;
    DROP TABLE IF EXISTS tmp_Button_Icon;
    
    CREATE TEMPORARY TABLE tmp_Button_Icon (
          id_temp INT
        , id_button_icon INT
        , id_image INT
        , code VARCHAR(250)
        , name VARCHAR(250)
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)
    );

    CREATE TEMPORARY TABLE tmp_Button_Icon_Copy (
          id_temp INT
        , id_button_icon INT
        , id_image INT
        , code VARCHAR(250)
        , name VARCHAR(250)
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)
    );
        
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
		  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT
        , code VARCHAR(250)
        , msg TEXT NOT NULL
	);
        
    
    -- Get data from Temp table
    INSERT INTO tmp_Button_Icon (
		  id_temp
        , id_button_icon
        , id_image
        , code
        , name
        , active
        , is_new
	)
    SELECT 
		  BUTTON_ICONS_T.id_temp
		, COALESCE(
              BUTTON_ICONS.id_button_icon
            , BUTTON_ICONS_T.id_button_icon
        ) AS id_button_icon
        , CASE WHEN IFNULL(BUTTON_ICONS_T.id_image, 0) < 1 THEN NULL ELSE BUTTON_ICONS_T.id_image END AS id_image
        , COALESCE(
              BUTTON_ICONS_T.code
            , BUTTON_ICONS.code
        ) AS code
        , COALESCE(
              BUTTON_ICONS_T.name
            , BUTTON_ICONS.name
        ) AS name
        , COALESCE(BUTTON_ICONS_T.active, 1) AS active
        , CASE WHEN COALESCE(BUTTON_ICONS.id_button_icon, BUTTON_ICONS_T.id_button_icon, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM fetchmetrics.DOG_Button_Icon_Temp BUTTON_ICONS_T
    LEFT JOIN fetchmetrics.DOG_Button_Icon BUTTON_ICONS 
        ON  BUTTON_ICONS_T.id_button_icon = BUTTON_ICONS.id_button_icon
        OR  (
                BUTTON_ICONS_T.name = BUTTON_ICONS.name
        )
    WHERE BUTTON_ICONS_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Button_Icon_Temp records';
        SELECT * FROM tmp_Button_Icon;
        SELECT COUNT(*) FROM tmp_Button_Icon;
    END IF;

    -- Error names
    UPDATE tmp_Button_Icon t_BUTTON_ICONS
    SET t_BUTTON_ICONS.name_error = COALESCE(t_BUTTON_ICONS.name, t_BUTTON_ICONS.code, t_BUTTON_ICONS.id_button_icon, '(No Button_Icon)')
    ;

    IF a_debug = 1 THEN
        SELECT 'After set name_error';
        SELECT * FROM tmp_Button_Icon;
        SELECT COUNT(*) FROM tmp_Button_Icon;
    END IF;

    -- Validation
    -- Missing mandatory fields
    -- code
    IF EXISTS ( SELECT * FROM tmp_Button_Icon t_BUTTON_ICONS WHERE t_BUTTON_ICONS.code IS NULL ) THEN
        INSERT INTO tmp_Msg_Error (
            id_type
            , code
            , msg
        )
        SELECT
            v_id_type_error_bad_data
            , v_code_type_error_bad_data
            , CONCAT('The following Button_Icon(s) do not have a valid Code: ', GROUP_CONCAT(t_BUTTON_ICONS.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Button_Icon t_BUTTON_ICONS
        WHERE t_BUTTON_ICONS.code IS NULL
        ;
    END IF;
    -- name
    IF EXISTS ( SELECT * FROM tmp_Button_Icon t_BUTTON_ICONS WHERE t_BUTTON_ICONS.name IS NULL ) THEN
        INSERT INTO tmp_Msg_Error (
            id_type
            , name
            , msg
        )
        SELECT
            v_id_type_error_bad_data
            , v_name_type_error_bad_data
            , CONCAT('The following Button_Icon(s) do not have a valid Name: ', GROUP_CONCAT(t_BUTTON_ICONS.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Button_Icon t_BUTTON_ICONS
        WHERE t_BUTTON_ICONS.name IS NULL
        ;
    END IF;

    -- Duplicates
    -- Duplicate names
    INSERT INTO tmp_Button_Icon_Copy (
        id_temp
        , id_button_icon
        , id_image
        , code
        , name
        , active
        , is_new
        , name_error
    )
    SELECT 
          t_BUTTON_ICONS.id_temp
        , t_BUTTON_ICONS.id_button_icon
        , t_BUTTON_ICONS.id_image
        , t_BUTTON_ICONS.code
        , t_BUTTON_ICONS.name
        , t_BUTTON_ICONS.active
        , t_BUTTON_ICONS.is_new
        , t_BUTTON_ICONS.name_error
    FROM tmp_Button_Icon t_BUTTON_ICONS
    ;

    IF a_debug = 1 THEN
        SELECT COUNT(*) AS Count_Temp_Button_Icon FROM tmp_Button_Icon;
        SELECT COUNT(*) AS Count_Temp_Button_Icon_Copy FROM tmp_Button_Icon_Copy;

        WITH 
              Combined_Button_Icons AS (
                SELECT 
                      BUTTON_ICONS.id_button_icon
                    , BUTTON_ICONS.name
                    , COALESCE(t_BUTTON_ICONS_COPY.name, t_BUTTON_ICONS_COPY.code, t_BUTTON_ICONS_COPY.id_button_icon, '(No Button_Icon)') AS name_error
                FROM fetchmetrics.DOG_Button_Icon BUTTON_ICONS 
                LEFT JOIN tmp_Button_Icon_Copy t_BUTTON_ICONS_COPY ON BUTTON_ICONS.name = t_BUTTON_ICONS_COPY.name
                WHERE t_BUTTON_ICONS_COPY.is_new = 1
                UNION
                SELECT 
                      t_BUTTON_ICONS.id_button_icon
                    , t_BUTTON_ICONS.name
                    , t_BUTTON_ICONS.name_error
                FROM tmp_Button_Icon t_BUTTON_ICONS
            )
            , Duplicate_Button_Icon_Name_Row_Numbers AS (
                SELECT 
                      COMBINED_BUTTON_ICONS.id_button_icon
                    , COMBINED_BUTTON_ICONS.name
                    , COMBINED_BUTTON_ICONS.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_BUTTON_ICONS.name ORDER BY COMBINED_BUTTON_ICONS.name_error ASC) AS index_button_icon_name_as_duplicate
                FROM Combined_Button_Icons COMBINED_BUTTON_ICONS
            )
        SELECT *
        FROM Duplicate_Button_Icon_Name_Row_Numbers
        ;
    END IF;
    
    IF EXISTS (
        WITH 
              Combined_Button_Icons AS (
                SELECT 
                      BUTTON_ICONS.id_button_icon
                    , BUTTON_ICONS.name
                    , COALESCE(t_BUTTON_ICONS_COPY.name, t_BUTTON_ICONS_COPY.code, t_BUTTON_ICONS_COPY.id_button_icon, '(No Button_Icon)') AS name_error
                FROM fetchmetrics.DOG_Button_Icon BUTTON_ICONS 
                LEFT JOIN tmp_Button_Icon_Copy t_BUTTON_ICONS_COPY ON BUTTON_ICONS.name = t_BUTTON_ICONS_COPY.name
                WHERE t_BUTTON_ICONS_COPY.is_new = 1
                UNION
                SELECT 
                      t_BUTTON_ICONS.id_button_icon
                    , t_BUTTON_ICONS.name
                    , t_BUTTON_ICONS.name_error
                FROM tmp_Button_Icon t_BUTTON_ICONS
            )
            , Duplicate_Button_Icon_Name_Row_Numbers AS (
                SELECT 
                      COMBINED_BUTTON_ICONS.id_button_icon
                    , COMBINED_BUTTON_ICONS.name
                    , COMBINED_BUTTON_ICONS.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_BUTTON_ICONS.name ORDER BY COMBINED_BUTTON_ICONS.name_error ASC) AS index_button_icon_name_as_duplicate
                FROM Combined_Button_Icons COMBINED_BUTTON_ICONS
            )
        SELECT *
        FROM Duplicate_Button_Icon_Name_Row_Numbers DUPLICATE_BUTTON_ICONS
        WHERE DUPLICATE_BUTTON_ICONS.index_button_icon_name_as_duplicate > 1
        GROUP BY DUPLICATE_BUTTON_ICONS.name
    ) THEN
        INSERT INTO tmp_Msg_Error (
              id_type
            , code
            , msg
        )
        WITH 
              Combined_Button_Icons AS (
                SELECT 
                      BUTTON_ICONS.id_button_icon
                    , BUTTON_ICONS.name
                    , COALESCE(t_BUTTON_ICONS_COPY.name, t_BUTTON_ICONS_COPY.code, t_BUTTON_ICONS_COPY.id_button_icon, '(No Button_Icon)') AS name_error
                FROM fetchmetrics.DOG_Button_Icon BUTTON_ICONS 
                LEFT JOIN tmp_Button_Icon_Copy t_BUTTON_ICONS_COPY ON BUTTON_ICONS.name = t_BUTTON_ICONS_COPY.name
                WHERE t_BUTTON_ICONS_COPY.is_new = 1
                UNION
                SELECT 
                      t_BUTTON_ICONS.id_button_icon
                    , t_BUTTON_ICONS.name
                    , t_BUTTON_ICONS.name_error
                FROM tmp_Button_Icon t_BUTTON_ICONS
            )
            , Duplicate_Button_Icon_Name_Row_Numbers AS (
                SELECT 
                      COMBINED_BUTTON_ICONS.id_button_icon
                    , COMBINED_BUTTON_ICONS.name
                    , COMBINED_BUTTON_ICONS.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_BUTTON_ICONS.name ORDER BY COMBINED_BUTTON_ICONS.name_error ASC) AS index_button_icon_name_as_duplicate
                FROM Combined_Button_Icons COMBINED_BUTTON_ICONS
            )
        SELECT
              v_id_type_error_bad_data
            , v_code_type_error_bad_data
            , CONCAT('Attempt to create duplicate or overwrite existing Button_Icons on: ', GROUP_CONCAT(DUPLICATE_BUTTON_ICONS.name_error SEPARATOR ', ')) AS msg
        FROM Duplicate_Button_Icon_Name_Row_Numbers DUPLICATE_BUTTON_ICONS
        WHERE DUPLICATE_BUTTON_ICONS.index_button_icon_as_duplicate > 1
        GROUP BY DUPLICATE_BUTTON_ICONS.name
        ;
    END IF;
    
    -- Permissions
    -- Can Create
	CALL fetchmetrics.p_dog_calc_user(
          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_new -- ids_permission
        , v_id_access_level_edit -- ids_access_level
        , 0 -- a_show_errors
        , 0 -- a_debug
    );
	
    SELECT
          IFNULL(CU_T.has_access, 0)
    INTO
          v_can_create
    FROM fetchmetrics.DOG_Calc_User_Temp CU_T
    WHERE CU_T.GUID = a_guid
    LIMIT 1
    ;
	
	CALL fetchmetrics.p_dog_clear_calc_user(
		  a_guid
        , 0 -- a_debug
	);
    
    IF v_can_create = 0 THEN
		DELETE t_ME
        FROM tmp_Msg_Error t_ME
        WHERE t_ME.id_type <> v_id_type_error_no_permission
        ;
		INSERT INTO tmp_Msg_Error (
			  id_type
            , code
			, msg
		)
		VALUES (
			  v_id_type_error_no_permission
            , v_code_type_error_no_permission
			, 'You do not have permission to edit Button_Icons.'
		)
        ;
    END IF;

    IF EXISTS (SELECT * FROM tmp_Msg_Error 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_Button_Icon;
	    END IF;

        DELETE FROM tmp_Button_Icon;
    END IF;

    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error 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
		START TRANSACTION;
		
			INSERT INTO fetchmetrics.DOG_Dog_Change_Set ( 
                  comment
                , id_user_updated_last_by
                , updated_last_on
            )
			VALUES ( 
                  a_comment
                , a_id_user
                , v_time_start
            )
			;
			
			SET v_id_change_set := LAST_INSERT_ID();
			
			UPDATE fetchmetrics.DOG_Button_Icon BUTTON_ICONS
			INNER JOIN tmp_Button_Icon t_BUTTON_ICONS 
				ON  BUTTON_ICONS.id_button_icon = t_BUTTON_ICONS.id_button_icon
				AND t_BUTTON_ICONS.is_new = 0
			SET 
				  BUTTON_ICONS.id_image = t_BUTTON_ICONS.id_image
				, BUTTON_ICONS.code = t_BUTTON_ICONS.code
				, BUTTON_ICONS.name = t_BUTTON_ICONS.name
				, BUTTON_ICONS.active = t_BUTTON_ICONS.active
				, BUTTON_ICONS.id_change_set = v_id_change_set
			;
			
			INSERT INTO fetchmetrics.DOG_Button_Icon (
				  id_image
				, code
				, name
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_BUTTON_ICONS.id_image                     AS id_image
				, t_BUTTON_ICONS.code                      AS code
				, t_BUTTON_ICONS.name                      AS name
				, t_BUTTON_ICONS.active                      AS active
				, a_id_user                                     AS created_by
				, v_time_start                                  AS created_on
			FROM tmp_Button_Icon t_BUTTON_ICONS
			WHERE 
				    t_BUTTON_ICONS.is_new = 1
				AND t_BUTTON_ICONS.active = 1
			;
			
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM fetchmetrics.DOG_Button_Icon_Temp
		WHERE GUID = a_guid
        ;
		
	COMMIT;
    
    -- Errors
    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 t_ERROR
	INNER JOIN fetchmetrics.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
	;
    
	IF a_debug = 1 THEN
		SELECT * FROM tmp_Button_Icon;
	END IF;

    DROP TEMPORARY TABLE tmp_Button_Icon;
    DROP TEMPORARY TABLE tmp_Msg_Error;
    
	IF a_debug = 1 THEN
		CALL fetchmetrics.p_core_debug_timing_reporting ( v_time_start );
	END IF;
END //
DELIMITER ;



/*

'ripplesipplenippletippledippsykippsy'
DELETE FROM fetchmetrics.DOG_Button_Icon WHERE id_button_icon > 740;
* /
delete
from fetchmetrics.DOG_Button_Icon_Audit
where id_button_icon > 768
;
delete
from fetchmetrics.DOG_Button_Icon
where id_button_icon > 768
;
delete
from fetchmetrics.DOG_Button_Icon_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Button_Icon_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Button_Icon_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Button_Icon
;
select COUNT(*)
from fetchmetrics.DOG_Button_Icon
;

INSERT INTO fetchmetrics.DOG_Button_Icon_Temp (
      id_button_icon
    , id_image
    , code
    , name
    , active
    , guid
)
VALUES (
      -1 -- id_button_icon
    , NULL -- id_image
    , 'NONE' -- code
    , 'None' -- name
    , 1 -- active
    , 'ripplesipplenippletippledippsykippsy'
);

CALL fetchmetrics.p_dog_save_button_icon (
	'nipples'
    , 'ripplesipplenippletippledippsykippsy'
    , 1
    , 1
);


select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Button_Icon_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Button_Icon_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Button_Icon
;
select COUNT(*)
from fetchmetrics.DOG_Button_Icon
;

*/