
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_save_distraction;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_save_distraction (
    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
        ;

        START TRANSACTION;
            INSERT INTO fetchmetrics.DOG_Msg_Error_Temp (
                id_type
                , code
                , msg
                , guid
            )
            SELECT
                t_ERROR.id_type
                , t_ERROR.code
                , t_ERROR.msg
                , a_guid
            FROM tmp_Msg_Error t_ERROR
            ;
        COMMIT;

		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_Distraction_Copy;
    DROP TABLE IF EXISTS tmp_Distraction;
    
    CREATE TEMPORARY TABLE tmp_Distraction (
          id_temp INT
		, id_distraction INT 
		, id_assessment INT
		, id_distraction_type INT
        , id_intensity_level_emotional INT
        , id_intensity_level_scent INT
        , id_intensity_level_sight INT
        , id_intensity_level_sound INT
        , id_intensity_level_touch INT
        , quantity INT
        , proximity_metres FLOAT
        , notes TEXT
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)
    );

    CREATE TEMPORARY TABLE tmp_Distraction_Copy (
          id_temp INT
		, id_distraction INT
		, id_assessment INT
		, id_distraction_type INT
        , id_intensity_level_emotional INT
        , id_intensity_level_scent INT
        , id_intensity_level_sight INT
        , id_intensity_level_sound INT
        , id_intensity_level_touch INT
        , quantity INT
        , proximity_metres FLOAT
        , notes TEXT
        , 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_Distraction (
		  id_temp
        , id_distraction
        , id_assessment
        , id_distraction_type
        , id_intensity_level_emotional
        , id_intensity_level_scent
        , id_intensity_level_sight
        , id_intensity_level_sound
        , id_intensity_level_touch
        , quantity
        , proximity_metres
        , notes
        , active
        , is_new
	)
    SELECT 
		  DISTRACTION_T.id_temp
		, DISTRACTION_T.id_distraction
        , COALESCE(
              DISTRACTION_T.id_assessment
            , DISTRACTION.id_assessment
        ) AS id_assessment
        , COALESCE(
              DISTRACTION_T.id_distraction_type
            , DISTRACTION.id_distraction_type
        ) AS id_distraction_type
        , COALESCE(
              DISTRACTION_T.id_intensity_level_emotional
            , DISTRACTION.id_intensity_level_emotional
        ) AS id_intensity_level_emotional
        , COALESCE(
              DISTRACTION_T.id_intensity_level_scent
            , DISTRACTION.id_intensity_level_scent
        ) AS id_intensity_level_scent
        , COALESCE(
              DISTRACTION_T.id_intensity_level_sight
            , DISTRACTION.id_intensity_level_sight
        ) AS id_intensity_level_sight
        , COALESCE(
              DISTRACTION_T.id_intensity_level_sound
            , DISTRACTION.id_intensity_level_sound
        ) AS id_intensity_level_sound
        , COALESCE(
              DISTRACTION_T.id_intensity_level_touch
            , DISTRACTION.id_intensity_level_touch
        ) AS id_intensity_level_touch
        , DISTRACTION_T.quantity
        , DISTRACTION_T.proximity_metres
        , DISTRACTION_T.notes
        , COALESCE(DISTRACTION_T.active, 1) AS active
        , CASE WHEN COALESCE(DISTRACTION_T.id_distraction, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM fetchmetrics.DOG_Distraction_Temp DISTRACTION_T
    LEFT JOIN fetchmetrics.DOG_Distraction DISTRACTION ON  DISTRACTION_T.id_distraction = DISTRACTION.id_distraction
    WHERE DISTRACTION_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Distraction_Temp records';
        SELECT * FROM tmp_Distraction;
        SELECT COUNT(*) FROM tmp_Distraction;
    END IF;

    -- Error names
    UPDATE tmp_Distraction t_DISTRACTION
    LEFT JOIN fetchmetrics.DOG_Distraction_Type DISTRACTION_TYPE ON t_DISTRACTION.id_distraction_type = DISTRACTION_TYPE.id_type
    LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_EMOTIONAL ON t_DISTRACTION.id_intensity_level_emotional = DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.id_intensity_level
    LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SCENT ON t_DISTRACTION.id_intensity_level_scent = DISTRACTION_INTENSITY_LEVEL_SCENT.id_intensity_level
    LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SIGHT ON t_DISTRACTION.id_intensity_level_sight = DISTRACTION_INTENSITY_LEVEL_SIGHT.id_intensity_level
    LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SOUND ON t_DISTRACTION.id_intensity_level_sound = DISTRACTION_INTENSITY_LEVEL_SOUND.id_intensity_level
    LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_TOUCH ON t_DISTRACTION.id_intensity_level_touch = DISTRACTION_INTENSITY_LEVEL_TOUCH.id_intensity_level
    SET t_DISTRACTION.name_error = CONCAT(
        /*
          CONVERT(COALESCE(t_DISTRACTION.created_on, DISTRACTION.created_on, v_time_start), CHAR)
        , CASE WHEN t_DISTRACTION.notes IS NOT NULL THEN CONCAT(' - ', t_DISTRACTION.notes) ELSE '' END
        */
          COALESCE(DISTRACTION_TYPE.name, '(No Distraction Type)')
        , ' - '
        , COALESCE(DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.name, '(No Distraction Intensity Level Emotional)')
        , ' - '
        , COALESCE(DISTRACTION_INTENSITY_LEVEL_SCENT.name, '(No Distraction Intensity Level Scent)')
        , ' - '
        , COALESCE(DISTRACTION_INTENSITY_LEVEL_SCENT.name, '(No Distraction Intensity Level Sight)')
        , ' - '
        , COALESCE(DISTRACTION_INTENSITY_LEVEL_SCENT.name, '(No Distraction Intensity Level Sound)')
        , ' - '
        , COALESCE(DISTRACTION_INTENSITY_LEVEL_SCENT.name, '(No Distraction Intensity Level Touch)')
        , ' - x'
        , CONVERT(COALESCE(t_DISTRACTION.quantity, 0), CHAR)
    )
    ;

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

    -- Validation
    -- Missing mandatory fields
    -- id_assessment
    IF EXISTS (
        SELECT *
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN demo.DOG_Assessment ASSESSMENT ON t_DISTRACTION.id_assessment = ASSESSMENT.id_assessment
        WHERE 
                ISNULL(t_DISTRACTION.id_assessment)
            OR  ISNULL(ASSESSMENT.id_assessment)
            OR  ASSESSMENT.active = 0
    ) 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 Dog Assessment Distraction(s) do not have a valid Assessment: ', GROUP_CONCAT(t_DISTRACTION.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN fetchmetrics.DOG_Assessment ASSESSMENT ON t_DISTRACTION.id_assessment = ASSESSMENT.id_assessment
        WHERE 
                ISNULL(t_DISTRACTION.id_assessment)
            OR  ISNULL(ASSESSMENT.id_assessment)
            OR  ASSESSMENT.active = 0
        ;
    END IF;
    -- id_distraction_type
    IF EXISTS (
        SELECT *
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN demo.DOG_Distraction_Type DISTRACTION_TYPE ON t_DISTRACTION.id_distraction_type = DISTRACTION_TYPE.id_type
        WHERE 
                ISNULL(t_DISTRACTION.id_distraction_type)
            OR  ISNULL(DISTRACTION_TYPE.id_type)
            OR  DISTRACTION_TYPE.active = 0
    ) 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 Dog Distraction_Type Distraction(s) do not have a valid Distraction_Type: ', GROUP_CONCAT(t_DISTRACTION.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN fetchmetrics.DOG_Distraction_Type DISTRACTION_TYPE ON t_DISTRACTION.id_distraction_type = DISTRACTION_TYPE.id_type
        WHERE 
                ISNULL(t_DISTRACTION.id_distraction_type)
            OR  ISNULL(DISTRACTION_TYPE.id_type)
            OR  DISTRACTION_TYPE.active = 0
        ;
    END IF;
    -- id_intensity_level_emotional
    IF EXISTS (
        SELECT *
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN demo.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_EMOTIONAL ON t_DISTRACTION.id_intensity_level_emotional = DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_emotional)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.active = 0
    ) 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 Distraction(s) do not have a valid Distraction_Intensity_Level_Emotional: ', GROUP_CONCAT(t_DISTRACTION.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_EMOTIONAL ON t_DISTRACTION.id_intensity_level_emotional = DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_emotional)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_EMOTIONAL.active = 0
        ;
    END IF;
    -- id_intensity_level_scent
    IF EXISTS (
        SELECT *
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN demo.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SCENT ON t_DISTRACTION.id_intensity_level_scent = DISTRACTION_INTENSITY_LEVEL_SCENT.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_scent)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_SCENT.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_SCENT.active = 0
    ) 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 Distraction(s) do not have a valid Intensity Level Scent: ', GROUP_CONCAT(t_DISTRACTION.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SCENT ON t_DISTRACTION.id_intensity_level_scent = DISTRACTION_INTENSITY_LEVEL_SCENT.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_scent)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_SCENT.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_SCENT.active = 0
        ;
    END IF;
    -- id_intensity_level_sight
    IF EXISTS (
        SELECT *
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN demo.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SIGHT ON t_DISTRACTION.id_intensity_level_sight = DISTRACTION_INTENSITY_LEVEL_SIGHT.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_sight)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_SIGHT.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_SIGHT.active = 0
    ) 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 Distraction(s) do not have a valid Intensity Level Sight: ', GROUP_CONCAT(t_DISTRACTION.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SIGHT ON t_DISTRACTION.id_intensity_level_sight = DISTRACTION_INTENSITY_LEVEL_SIGHT.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_sight)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_SIGHT.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_SIGHT.active = 0
        ;
    END IF;
    -- id_intensity_level_sound
    IF EXISTS (
        SELECT *
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN demo.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SOUND ON t_DISTRACTION.id_intensity_level_sound = DISTRACTION_INTENSITY_LEVEL_SOUND.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_sound)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_SOUND.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_SOUND.active = 0
    ) 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 Distraction(s) do not have a valid Intensity Level Sound: ', GROUP_CONCAT(t_DISTRACTION.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_SOUND ON t_DISTRACTION.id_intensity_level_sound = DISTRACTION_INTENSITY_LEVEL_SOUND.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_sound)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_SOUND.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_SOUND.active = 0
        ;
    END IF;
    -- id_intensity_level_touch
    IF EXISTS (
        SELECT *
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN demo.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_TOUCH ON t_DISTRACTION.id_intensity_level_touch = DISTRACTION_INTENSITY_LEVEL_TOUCH.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_touch)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_TOUCH.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_TOUCH.active = 0
    ) 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 Distraction(s) do not have a valid Intensity Level Touch: ', GROUP_CONCAT(t_DISTRACTION.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Distraction t_DISTRACTION
        LEFT JOIN fetchmetrics.DOG_Distraction_Intensity_Level DISTRACTION_INTENSITY_LEVEL_TOUCH ON t_DISTRACTION.id_intensity_level_touch = DISTRACTION_INTENSITY_LEVEL_TOUCH.id_intensity_level
        WHERE 
                ISNULL(t_DISTRACTION.id_intensity_level_touch)
            OR  ISNULL(DISTRACTION_INTENSITY_LEVEL_TOUCH.id_intensity_level)
            OR  DISTRACTION_INTENSITY_LEVEL_TOUCH.active = 0
        ;
    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 Distractions.'
		)
        ;
    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_Distraction;
	    END IF;

        DELETE FROM tmp_Distraction;
    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_Distraction DISTRACTION
			INNER JOIN tmp_Distraction t_DISTRACTION 
				ON  DISTRACTION.id_distraction = t_DISTRACTION.id_distraction
				AND t_DISTRACTION.is_new = 0
			SET 
				  DISTRACTION.id_assessment = t_DISTRACTION.id_assessment
				, DISTRACTION.id_distraction_type = t_DISTRACTION.id_distraction_type
				, DISTRACTION.id_intensity_level_emotional = t_DISTRACTION.id_intensity_level_emotional
				, DISTRACTION.id_intensity_level_scent = t_DISTRACTION.id_intensity_level_scent
				, DISTRACTION.id_intensity_level_sight = t_DISTRACTION.id_intensity_level_sight
				, DISTRACTION.id_intensity_level_sound = t_DISTRACTION.id_intensity_level_sound
				, DISTRACTION.id_intensity_level_touch = t_DISTRACTION.id_intensity_level_touch
				, DISTRACTION.quantity = t_DISTRACTION.quantity
				, DISTRACTION.proximity_metres = t_DISTRACTION.proximity_metres
                , DISTRACTION.notes = t_DISTRACTION.notes
				, DISTRACTION.active = t_DISTRACTION.active
				, DISTRACTION.id_change_set = v_id_change_set
			;
			
			INSERT INTO fetchmetrics.DOG_Distraction (
				  id_temp
                , id_assessment
				, id_distraction_type
				, id_intensity_level_emotional
				, id_intensity_level_scent
				, id_intensity_level_sight
				, id_intensity_level_sound
				, id_intensity_level_touch
				, quantity
				, proximity_metres
                , notes
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_DISTRACTION.id_temp
                , t_DISTRACTION.id_assessment                     AS id_assessment
				, t_DISTRACTION.id_distraction_type                   AS id_distraction_type
				, t_DISTRACTION.id_intensity_level_emotional     AS id_intensity_level_emotional
				, t_DISTRACTION.id_intensity_level_scent     AS id_intensity_level_scent
				, t_DISTRACTION.id_intensity_level_sight     AS id_intensity_level_sight
				, t_DISTRACTION.id_intensity_level_sound     AS id_intensity_level_sound
				, t_DISTRACTION.id_intensity_level_touch     AS id_intensity_level_touch
				, t_DISTRACTION.quantity     AS quantity
				, t_DISTRACTION.proximity_metres     AS proximity_metres
                , t_DISTRACTION.notes                       AS notes
				, t_DISTRACTION.active                      AS active
				, a_id_user                                     AS created_by
				, v_time_start                                  AS created_on
			FROM tmp_Distraction t_DISTRACTION
			WHERE 
				    t_DISTRACTION.is_new = 1
				AND t_DISTRACTION.active = 1
			;

            INSERT INTO fetchmetrics.DOG_Msg_Error_Temp (
                id_type
                , code
                , msg
                , guid
            )
            SELECT
                t_ERROR.id_type
                , t_ERROR.code
                , t_ERROR.msg
                , a_guid
            FROM tmp_Msg_Error t_ERROR
            ;
			
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM fetchmetrics.DOG_Distraction_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_Distraction;
	END IF;

    DROP TEMPORARY TABLE tmp_Distraction;
    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 ;



/*

'ripplesipplenippletippledipplekipple'
DELETE FROM fetchmetrics.DOG_Distraction WHERE id_distraction > 740;
* /
delete
from fetchmetrics.DOG_Distraction_Audit
where id_distraction > 768
;
delete
from fetchmetrics.DOG_Distraction
where id_distraction > 768
;
delete
from fetchmetrics.DOG_Distraction_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Distraction_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Distraction_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Distraction
;
select COUNT(*)
from fetchmetrics.DOG_Distraction
;

INSERT INTO fetchmetrics.DOG_Distraction_Temp (
      id_distraction
    , id_dog
    , id_command
    , hand_signal_description
    , notes
    , active
    , guid
)
VALUES (
      -1 -- id_distraction
    , 1 -- id_dog
    , 1 -- id_command
    , 'Test deez noots' -- hand_signal_description
    , NULL -- notes
    , 1 -- active
    , 'ripplesipplenippletippledipplekipple'
);

CALL fetchmetrics.p_dog_save_distraction (
	'nipples'
    , 'ripplesipplenippletippledipplekipple'
    , 1
    , 1
);


select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Distraction_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Distraction_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Distraction
;
select COUNT(*)
from fetchmetrics.DOG_Distraction
;

*/