
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_save_assessment_response;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_save_assessment_response (
    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_Assessment_Response_Copy;
    DROP TABLE IF EXISTS tmp_Assessment_Response;
    
    CREATE TEMPORARY TABLE tmp_Assessment_Response (
          id_temp INT
		, id_response INT 
        , id_assessment_command_modality_link INT
        , id_response_quality_metric INT
        , id_obedience_level INT
        , value_measured DOUBLE
        , notes TEXT
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)
    );

    CREATE TEMPORARY TABLE tmp_Assessment_Response_Copy (
          id_temp INT
		, id_response INT
		, id_assessment_command_modality_link INT
		, id_response_quality_metric INT
        , id_obedience_level INT
        , value_measured DOUBLE
        , 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_Assessment_Response (
		  id_temp
        , id_response
        , id_assessment_command_modality_link
        , id_response_quality_metric
        , id_obedience_level
        , value_measured
        , notes
        , active
        , is_new
	)
    SELECT 
		  ASSESSMENT_RESPONSE_T.id_temp
		, ASSESSMENT_RESPONSE_T.id_response
        , COALESCE(
              ASSESSMENT_RESPONSE_T.id_assessment_command_modality_link
            , ASSESSMENT_RESPONSE.id_assessment_command_modality_link
        ) AS id_assessment_command_modality_link
        , COALESCE(
              ASSESSMENT_RESPONSE_T.id_response_quality_metric
            , ASSESSMENT_RESPONSE.id_response_quality_metric
        ) AS id_response_quality_metric
        , COALESCE(
              ASSESSMENT_RESPONSE_T.id_obedience_level
            , ASSESSMENT_RESPONSE.id_obedience_level
        ) AS id_obedience_level
        , ASSESSMENT_RESPONSE_T.value_measured
        , ASSESSMENT_RESPONSE_T.notes
        , COALESCE(
              ASSESSMENT_RESPONSE_T.active
            , ASSESSMENT_RESPONSE.active
            , 1
        ) AS active
        , CASE WHEN COALESCE(ASSESSMENT_RESPONSE_T.id_response, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM fetchmetrics.DOG_Assessment_Response_Temp ASSESSMENT_RESPONSE_T
    LEFT JOIN fetchmetrics.DOG_Assessment_Response ASSESSMENT_RESPONSE ON  ASSESSMENT_RESPONSE_T.id_response = ASSESSMENT_RESPONSE.id_response
    WHERE ASSESSMENT_RESPONSE_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Assessment_Response_Temp records';
        SELECT * FROM tmp_Assessment_Response;
        SELECT COUNT(*) FROM tmp_Assessment_Response;
    END IF;

    -- Error names
    UPDATE tmp_Assessment_Response t_ASSESSMENT_RESPONSE
    LEFT JOIN fetchmetrics.DOG_Assessment_Command_Modality_Link ASSESSMENT_COMMAND_MODALITY_LINK ON t_ASSESSMENT_RESPONSE.id_assessment_command_modality_link = ASSESSMENT_COMMAND_MODALITY_LINK.id_link
    LEFT JOIN fetchmetrics.DOG_Response_Quality_Metric RESPONSE_QUALITY_METRIC ON t_ASSESSMENT_RESPONSE.id_response_quality_metric = RESPONSE_QUALITY_METRIC.id_metric
    LEFT JOIN fetchmetrics.DOG_Obedience_Level OBEDIENCE_LEVEL ON t_ASSESSMENT_RESPONSE.id_obedience_level = OBEDIENCE_LEVEL.id_obedience_level
    SET t_ASSESSMENT_RESPONSE.name_error = CONCAT(
          COALESCE(CONVERT(ASSESSMENT_COMMAND_MODALITY_LINK.created_on, CHAR), '(No Assessment Command Modality Link)')
        , ' - '
        , COALESCE(RESPONSE_QUALITY_METRIC.name, '(No Response Quality Metric)')
        , ' - '
        , COALESCE(OBEDIENCE_LEVEL.name, '(No Obedience Level)')
    )
    ;

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

    -- Validation
    -- Missing mandatory fields
    -- id_assessment_command_modality_link
    IF EXISTS (
        SELECT *
        FROM tmp_Assessment_Response t_ASSESSMENT_RESPONSE
        LEFT JOIN fetchmetrics.DOG_Assessment_Command_Modality_Link ASSESSMENT_COMMAND_MODALITY_LINK ON t_ASSESSMENT_RESPONSE.id_assessment_command_modality_link = ASSESSMENT_COMMAND_MODALITY_LINK.id_link
        WHERE 
                ISNULL(t_ASSESSMENT_RESPONSE.id_assessment_command_modality_link)
            OR  ISNULL(ASSESSMENT_COMMAND_MODALITY_LINK.id_link)
            OR  ASSESSMENT_COMMAND_MODALITY_LINK.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 Response(s) do not have a valid Assessment_Command_Modality_Link: ', GROUP_CONCAT(t_ASSESSMENT_RESPONSE.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Assessment_Response t_ASSESSMENT_RESPONSE
        LEFT JOIN fetchmetrics.DOG_Assessment_Command_Modality_Link ASSESSMENT_COMMAND_MODALITY_LINK ON t_ASSESSMENT_RESPONSE.id_assessment_command_modality_link = ASSESSMENT_COMMAND_MODALITY_LINK.id_link
        WHERE 
                ISNULL(t_ASSESSMENT_RESPONSE.id_assessment_command_modality_link)
            OR  ISNULL(ASSESSMENT_COMMAND_MODALITY_LINK.id_link)
            OR  ASSESSMENT_COMMAND_MODALITY_LINK.active = 0
        ;
    END IF;
    -- id_response_quality_metric
    IF EXISTS (
        SELECT *
        FROM tmp_Assessment_Response t_ASSESSMENT_RESPONSE
        LEFT JOIN fetchmetrics.DOG_Response_Quality_Metric RESPONSE_QUALITY_METRIC ON t_ASSESSMENT_RESPONSE.id_response_quality_metric = RESPONSE_QUALITY_METRIC.id_metric
        WHERE 
                ISNULL(t_ASSESSMENT_RESPONSE.id_response_quality_metric)
            OR  ISNULL(RESPONSE_QUALITY_METRIC.id_metric)
            OR  RESPONSE_QUALITY_METRIC.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 Response(s) do not have a valid Response_Quality_Metric: ', GROUP_CONCAT(t_ASSESSMENT_RESPONSE.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Assessment_Response t_ASSESSMENT_RESPONSE
        LEFT JOIN fetchmetrics.DOG_Response_Quality_Metric RESPONSE_QUALITY_METRIC ON t_ASSESSMENT_RESPONSE.id_response_quality_metric = RESPONSE_QUALITY_METRIC.id_metric
        WHERE 
                ISNULL(t_ASSESSMENT_RESPONSE.id_response_quality_metric)
            OR  ISNULL(RESPONSE_QUALITY_METRIC.id_metric)
            OR  RESPONSE_QUALITY_METRIC.active = 0
        ;
    END IF;
    -- id_obedience_level
    IF EXISTS (
        SELECT *
        FROM tmp_Assessment_Response t_ASSESSMENT_RESPONSE
        LEFT JOIN fetchmetrics.DOG_Obedience_Level OBEDIENCE_LEVEL ON t_ASSESSMENT_RESPONSE.id_obedience_level = OBEDIENCE_LEVEL.id_obedience_level
        WHERE 
                ISNULL(t_ASSESSMENT_RESPONSE.id_obedience_level)
            OR  ISNULL(OBEDIENCE_LEVEL.id_obedience_level)
            OR  OBEDIENCE_LEVEL.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 Response(s) do not have a valid Obedience Level: ', GROUP_CONCAT(t_ASSESSMENT_RESPONSE.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Assessment_Response t_ASSESSMENT_RESPONSE
        LEFT JOIN fetchmetrics.DOG_Obedience_Level OBEDIENCE_LEVEL ON t_ASSESSMENT_RESPONSE.id_obedience_level = OBEDIENCE_LEVEL.id_obedience_level
        WHERE 
                ISNULL(t_ASSESSMENT_RESPONSE.id_obedience_level)
            OR  ISNULL(OBEDIENCE_LEVEL.id_obedience_level)
            OR  OBEDIENCE_LEVEL.active = 0
        ;
    END IF;
    
    -- Permissions
    -- Can Create
	CALL fetchmetrics.p_dog_calc_user_access(
          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_Access_Temp CU_T
    WHERE CU_T.GUID = a_guid
    LIMIT 1
    ;
	
	CALL fetchmetrics.p_dog_clear_calc_user_access(
		  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 Assessment_Responses.'
		)
        ;
    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_Assessment_Response;
	    END IF;

        DELETE FROM tmp_Assessment_Response;
    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_Assessment_Response ASSESSMENT_RESPONSE
			INNER JOIN tmp_Assessment_Response t_ASSESSMENT_RESPONSE 
				ON  ASSESSMENT_RESPONSE.id_response = t_ASSESSMENT_RESPONSE.id_response
				AND t_ASSESSMENT_RESPONSE.is_new = 0
			SET 
				  ASSESSMENT_RESPONSE.id_assessment_command_modality_link = t_ASSESSMENT_RESPONSE.id_assessment_command_modality_link
				, ASSESSMENT_RESPONSE.id_response_quality_metric = t_ASSESSMENT_RESPONSE.id_response_quality_metric
				, ASSESSMENT_RESPONSE.id_obedience_level = t_ASSESSMENT_RESPONSE.id_obedience_level
				, ASSESSMENT_RESPONSE.value_measured = t_ASSESSMENT_RESPONSE.value_measured
				, ASSESSMENT_RESPONSE.notes = t_ASSESSMENT_RESPONSE.notes
				, ASSESSMENT_RESPONSE.active = t_ASSESSMENT_RESPONSE.active
				, ASSESSMENT_RESPONSE.id_change_set = v_id_change_set
			;
			
			INSERT INTO fetchmetrics.DOG_Assessment_Response (
				  id_temp
                , id_assessment_command_modality_link
				, id_response_quality_metric
				, id_obedience_level
				, value_measured
				, notes
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_ASSESSMENT_RESPONSE.id_temp
                , t_ASSESSMENT_RESPONSE.id_assessment_command_modality_link                     AS id_assessment_command_modality_link
				, t_ASSESSMENT_RESPONSE.id_response_quality_metric                   AS id_response_quality_metric
				, t_ASSESSMENT_RESPONSE.id_obedience_level     AS id_obedience_level
				, t_ASSESSMENT_RESPONSE.value_measured     AS value_measured
				, t_ASSESSMENT_RESPONSE.notes     AS notes
				, t_ASSESSMENT_RESPONSE.active                      AS active
				, a_id_user                                     AS created_by
				, v_time_start                                  AS created_on
			FROM tmp_Assessment_Response t_ASSESSMENT_RESPONSE
			WHERE 
				    t_ASSESSMENT_RESPONSE.is_new = 1
				AND t_ASSESSMENT_RESPONSE.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_Assessment_Response_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_Assessment_Response;
	END IF;

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



/*

'ripplesipplenipplytippledipplykipple'
DELETE FROM fetchmetrics.DOG_Assessment_Response WHERE id_response > 740;
* /
delete
from fetchmetrics.DOG_Assessment_Response_Audit
where id_response > 768
;
delete
from fetchmetrics.DOG_Assessment_Response
where id_response > 768
;
delete
from fetchmetrics.DOG_Assessment_Response_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment_Response_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Assessment_Response_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment_Response
;
select COUNT(*)
from fetchmetrics.DOG_Assessment_Response
;

INSERT INTO fetchmetrics.DOG_Assessment_Response_Temp (
      id_response
    , id_assessment_command_modality_link
    , id_response_quality_metric
    , id_obedience_level
    , value_measured
    , notes
    , active
    , guid
)
VALUES (
      -1 -- id_response
    , 1 -- id_assessment_command_modality_link
    , 1 -- id_response_quality_metric
    , 1 -- id_obedience_level
    , 10000 -- value_measured
    , 'suck balls' -- notes
    , 1 -- active
    , 'ripplesipplenipplytippledipplykipple'
);

CALL fetchmetrics.p_dog_save_assessment_response (
	'nipples'
    , 'ripplesipplenipplytippledipplykipple'
    , 1
    , 1
);


select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment_Response_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Assessment_Response_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment_Response
;
select COUNT(*)
from fetchmetrics.DOG_Assessment_Response
;

*/