
USE parts;

DROP PROCEDURE IF EXISTS parts.p_dog_save_command;

DELIMITER //
CREATE PROCEDURE parts.p_dog_save_command (
    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_admin INT;
    DECLARE v_id_access_level_edit INT;
    DECLARE v_id_change_set INT;
    DECLARE v_id_permission_dog_admin 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 NULL
			, code VARCHAR(100)
			, msg TEXT NOT NULL
		);

        INSERT INTO tmp_Msg_Error (
			  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 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;
    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 ERROR_TYPE.id_type FROM parts.CORE_Msg_Error_Type ERROR_TYPE WHERE ERROR_TYPE.code = v_code_type_error_bad_data LIMIT 1);
    SET v_id_permission_dog_admin := (SELECT PERMISSION.id_permission FROM parts.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_ADMIN' LIMIT 1);
    SET v_id_permission_dog_new := (SELECT PERMISSION.id_permission FROM parts.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_CREATE' LIMIT 1);
    SET v_id_access_level_admin := (SELECT ACCESS_LEVEL.id_access_level FROM parts.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'ADMIN' LIMIT 1);
    SET v_id_access_level_edit := (SELECT ACCESS_LEVEL.id_access_level FROM parts.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'EDIT' LIMIT 1);
    
    CALL parts.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Command;
    
    CREATE TEMPORARY TABLE tmp_Command (
          id_command INT
        , id_command_category INT
        , name VARCHAR(250)
        , hand_signal_default_description TEXT
        , can_have_button BIT
        , notes TEXT
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)

        , name_command_category VARCHAR(250)
    );
        
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp_Msg_Error (
		  id_error INT NOT NULL PRIMARY KEY AUTO_INCREMENT
		, id_type INT NULL
        , code VARCHAR(100)
        , msg TEXT NOT NULL
	);
        
    
    -- Get data from Temp table
    INSERT INTO tmp_Command (
		  id_command
        , id_command_category
        , name
        , hand_signal_default_description
        , can_have_button
        , notes
        , active
        , is_new

        , name_command_category
	)
    SELECT 
		  COMMAND_T.id_command AS id_command
        , COMMAND_T.id_command_category AS id_command_category
        , COALESCE(
              COMMAND_T.name
            , COMMAND.name
        ) AS name
        , COALESCE(
              COMMAND_T.hand_signal_default_description
            , COMMAND.hand_signal_default_description
        ) AS hand_signal_default_description
        , COALESCE(
              COMMAND_T.can_have_button
            , COMMAND.can_have_button
        ) AS can_have_button
        , COALESCE(
              COMMAND_T.notes
            , COMMAND.notes
        ) AS notes
        , COALESCE(
              COMMAND_T.active
            , COMMAND.active
            , 1
        ) AS active
        , CASE WHEN IFNULL(COMMAND_T.id_command, 0) < 1 THEN 1 ELSE 0 END AS is_new
        -- , CASE WHEN NOT ISNULL(COMMAND_T.id_command) THEN 1 ELSE 0 END AS does_have_valid_command_id

        , COMMAND_T.name_command_category AS name_command_category 
	FROM parts.DOG_Command_Temp COMMAND_T
    LEFT JOIN parts.DOG_Command COMMAND ON COMMAND_T.id_command = COMMAND.id_command
    WHERE COMMAND_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Command_Temp records';
        SELECT * FROM tmp_Command;
        SELECT COUNT(*) FROM tmp_Command;
    END IF;

    -- Error names
    UPDATE tmp_Command t_COMMAND
    LEFT JOIN parts.DOG_Command_Category COMMAND_CATEGORY ON t_COMMAND.id_command_category = COMMAND_CATEGORY.id_command_category
    LEFT JOIN parts.DOG_Command COMMAND ON t_COMMAND.id_command = COMMAND.id_command
    SET t_COMMAND.name_error = CONCAT(
          COALESCE(COMMAND_CATEGORY.name, t_COMMAND.id_command_category, '(No Command Category)')
        , ' - '
        , COALESCE(COMMAND.name, t_COMMAND.id_command, '(No Command)')
    )
    ;

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

    -- Find missing id_command_category by name_command_category
    UPDATE tmp_Command t_COMMAND
    INNER JOIN parts.DOG_Command_Category COMMAND_CATEGORY ON t_COMMAND.name_command_category = COMMAND_CATEGORY.name
    SET t_COMMAND.id_command_category = COMMAND_CATEGORY.id_command_category
    WHERE 
            t_COMMAND.id_command_category IS NULL
        AND COMMAND_CATEGORY.id_command_category IS NOT NULL
    ;

    IF a_debug = 1 THEN
        SELECT 'After set missing id_command_category from name';
        SELECT * FROM tmp_Command;
        SELECT COUNT(*) FROM tmp_Command;
    END IF;

    -- Missing Command Ids
    UPDATE tmp_Command t_COMMAND
    LEFT JOIN parts.DOG_Command COMMAND
        ON  t_COMMAND.id_command_category = COMMAND.id_command_category
        AND t_COMMAND.name = COMMAND.name
    SET 
        t_COMMAND.id_command = COMMAND.id_command
        , t_COMMAND.is_new = 0
    WHERE 
            IFNULL(t_COMMAND.id_command, 0) < 1
        AND NOT ISNULL(COMMAND.id_command)
    ;

    IF a_debug = 1 THEN
        SELECT 'After set missing id_command';
        SELECT * FROM tmp_Command;
        SELECT COUNT(*) FROM tmp_Command;
    END IF;
    
    -- Validation
    -- Missing mandatory fields
    -- id_command_category
    IF EXISTS (SELECT * FROM tmp_Command t_COMMAND WHERE ISNULL(t_COMMAND.id_command_category) LIMIT 1) 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 Command(s) do not have a Category: ', GROUP_CONCAT(t_COMMAND.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Command t_COMMAND
		WHERE ISNULL(t_COMMAND.id_command_category)
		;
    END IF;
    -- name
    IF EXISTS (SELECT * FROM tmp_Command t_COMMAND WHERE ISNULL(t_COMMAND.name) LIMIT 1) 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 Command(s) do not have a Name: ', GROUP_CONCAT(t_COMMAND.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Command t_COMMAND
		WHERE ISNULL(t_COMMAND.name)
		;
    END IF;
    -- can_have_button
    IF EXISTS (SELECT * FROM tmp_Command t_COMMAND WHERE ISNULL(t_COMMAND.can_have_button) LIMIT 1) 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 Command(s) do not have a Can-Have-Button: ', GROUP_CONCAT(t_COMMAND.name_error SEPARATOR ', ')) AS msg
		FROM tmp_Command t_COMMAND
		WHERE ISNULL(t_COMMAND.can_have_button)
		;
    END IF;
    
    -- Permissions
    -- Can Create
    IF a_debug = 1 THEN
		SELECT 
			  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
        ;
    END IF;
    
	CALL parts.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 parts.DOG_Calc_User_Temp CU_T
    WHERE CU_T.GUID = a_guid
    LIMIT 1
    ;
	
	CALL parts.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 new Commands.'
		)
        ;
    END IF;
    
    IF EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
    	IF a_debug = 1 THEN
	    	SELECT * from tmp_Command;
	    END IF;

        DELETE FROM tmp_Command;
    END IF;

    IF NOT EXISTS (SELECT * FROM tmp_Msg_Error t_ERROR INNER JOIN parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type WHERE ERROR_TYPE.is_breaking_error = 1 LIMIT 1) THEN
		START TRANSACTION;
		
			INSERT INTO parts.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 parts.DOG_Command COMMAND
			INNER JOIN tmp_Command t_COMMAND 
				ON  COMMAND.id_command = t_COMMAND.id_command
				AND t_COMMAND.is_new = 0
			SET 
				  COMMAND.id_command_category = t_COMMAND.id_command_category
				, COMMAND.name = t_COMMAND.name
				, COMMAND.hand_signal_default_description = t_COMMAND.hand_signal_default_description
				, COMMAND.can_have_button = t_COMMAND.can_have_button
                , COMMAND.notes = t_COMMAND.notes
				, COMMAND.active = t_COMMAND.active
				, COMMAND.id_change_set = v_id_change_set
			;
			
			INSERT INTO parts.DOG_Command (
				  id_command_category
				, name
				, hand_signal_default_description
				, can_have_button
                , notes
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_COMMAND.id_command_category         AS id_command_category
				, t_COMMAND.name                        AS name
				, t_COMMAND.hand_signal_default_description     AS hand_signal_default_description
				, t_COMMAND.can_have_button             AS can_have_button
                , t_COMMAND.notes                       AS notes
				, t_COMMAND.active                      AS active
				, a_id_user                             AS created_by
				, v_time_start                          AS created_on
			FROM tmp_Command t_COMMAND
			WHERE 
				    t_COMMAND.is_new = 1
				AND t_COMMAND.active = 1
			;
			
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM parts.DOG_Command_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 parts.CORE_Msg_Error_Type ERROR_TYPE ON t_ERROR.id_type = ERROR_TYPE.id_type
	;
    
	IF a_debug = 1 THEN
		SELECT * from tmp_Command;
	END IF;

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



/*

select 
	*
    -- COUNT(*)
-- delete
from parts.DOG_Command_Temp
;
select COUNT(*)
from parts.DOG_Command_Temp
;

*/




DELETE FROM demo.DOG_Command_Temp;
SELECT * 
	/*
    CC.name
	, C.name
    */
FROM parts.DOG_Command C
INNER JOIN parts.DOG_Command_Category CC ON C.id_command_category = CC.id_command_category
ORDER BY CC.name, C.name
;
select COUNT(*)
from parts.DOG_Command
;

INSERT INTO parts.DOG_Command_Temp (
      id_command
    , id_command_category
    , name
    , hand_signal_default_description
    , can_have_button
    , notes
    , active
    , guid
)
VALUES (
      -1 -- id_command
    , 1 -- id_command_category
    , 'Bathing' -- name
    , 'Burp and juice' -- hand_signal_default_description
    , 1 -- can_have_category
    , 'Sweet' -- notes
    , 1 -- active
    , 'ripplesipplenippletippledipplekipple'
);



CALL parts.p_dog_save_command (
	'ripplesipplenippletippledipplekipple'
    , (SELECT GUID FROM parts.DOG_Command_Temp COMMAND_TEMP ORDER BY id_temp DESC LIMIT 1)
    , 1
    , 1
);


select 
	*
    -- COUNT(*)
-- delete
from parts.DOG_Command_Temp
;
select COUNT(*)
from parts.DOG_Command_Temp
;
SELECT * 
	/*
    CC.name
	, C.name
    */
FROM parts.DOG_Command C
INNER JOIN parts.DOG_Command_Category CC ON C.id_command_category = CC.id_command_category
ORDER BY CC.name, C.name
;
select COUNT(*)
from parts.DOG_Command
;
