
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_save_assessment;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_save_assessment (
    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_Copy;
    DROP TABLE IF EXISTS tmp_Assessment;
    
    CREATE TEMPORARY TABLE tmp_Assessment (
          id_temp INT
		, id_assessment INT 
		, id_weather INT
        , id_lighting_level INT
        , id_location INT
        , id_user_handler INT
        , notes TEXT
        , temperature_celcius DECIMAL(5, 2)
        , difficulty_level FLOAT
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)
    );

    CREATE TEMPORARY TABLE tmp_Assessment_Copy (
          id_temp INT
		, id_assessment INT
		, id_weather INT
        , id_lighting_level INT
        , id_location INT
        , id_user_handler INT
        , notes TEXT
        , temperature_celcius DECIMAL(5, 2)
        , difficulty_level FLOAT
        , 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 (
		  id_temp
        , id_assessment
        , id_weather 
        , id_lighting_level
        , id_location 
        , id_user_handler
        , notes
        , temperature_celcius
        , difficulty_level
        , active
        , is_new
	)
    SELECT 
		  ASSESSMENT_T.id_temp
		, ASSESSMENT_T.id_assessment
        , COALESCE(
              ASSESSMENT_T.id_weather
            , ASSESSMENT.id_weather
        ) AS id_weather
        , COALESCE(
              ASSESSMENT_T.id_lighting_level
            , ASSESSMENT.id_lighting_level
        ) AS id_lighting_level
        , COALESCE(
              ASSESSMENT_T.id_location
            , ASSESSMENT.id_location
        ) AS id_location
        , COALESCE(
              ASSESSMENT_T.id_user_handler
            , ASSESSMENT.id_user_handler
        ) AS id_user_handler
        , ASSESSMENT_T.notes
        , ASSESSMENT_T.temperature_celcius
        , ASSESSMENT_T.difficulty_level
        , COALESCE(ASSESSMENT_T.active, 1) AS active
        , CASE WHEN COALESCE(ASSESSMENT_T.id_assessment, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM fetchmetrics.DOG_Assessment_Temp ASSESSMENT_T
    LEFT JOIN fetchmetrics.DOG_Assessment ASSESSMENT ON  ASSESSMENT_T.id_assessment = ASSESSMENT.id_assessment
    WHERE ASSESSMENT_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Assessment_Temp records';
        SELECT * FROM tmp_Assessment;
        SELECT COUNT(*) FROM tmp_Assessment;
    END IF;

    -- Error names
    UPDATE tmp_Assessment t_ASSESSMENT
    LEFT JOIN fetchmetrics.DOG_Assessment ASSESSMENT ON t_ASSESSMENT.id_assessment = ASSESSMENT.id_assessment
    SET t_ASSESSMENT.name_error = CONCAT(
          CONVERT(COALESCE(ASSESSMENT.created_on, v_time_start), CHAR)
        , CASE WHEN t_ASSESSMENT.notes IS NOT NULL THEN CONCAT(' - ', t_ASSESSMENT.notes) ELSE '' END
        /*
        COALESCE(WEATHER.name, '(No Weather)')
        , ' - '
        , COALESCE(LIGHTING_LEVEL.name, '(No Lighting Level)')
        , ' - '
        , COALESCE(LOCATIONS.name, '(No Location)')
        , ' - '
        , COALESCE(CONCAT(USER_HANDLER.firstname, ' ', USER_HANDLER.surname), '(No User Handler)')
        , ' - x'
        , CONVERT(COALESCE(t_ASSESSMENT.quantity, 0), CHAR)
        */
    )
    ;

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

    -- Validation
    -- Missing mandatory fields
    -- id_weather
    IF EXISTS (
        SELECT *
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_Weather WEATHER ON t_ASSESSMENT.id_weather = WEATHER.id_weather
        WHERE 
                ISNULL(t_ASSESSMENT.id_weather)
            OR  ISNULL(WEATHER.id_weather)
            OR  WEATHER.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 Weather Assessment(s) do not have a valid Weather: ', GROUP_CONCAT(t_ASSESSMENT.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_Weather WEATHER ON t_ASSESSMENT.id_weather = WEATHER.id_weather
        WHERE 
                ISNULL(t_ASSESSMENT.id_weather)
            OR  ISNULL(WEATHER.id_weather)
            OR  WEATHER.active = 0
        ;
    END IF;
    -- id_lighting_level
    IF EXISTS (
        SELECT *
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_Lighting_Level LIGHTING_LEVEL ON t_ASSESSMENT.id_lighting_level = LIGHTING_LEVEL.id_lighting_level
        WHERE 
                ISNULL(t_ASSESSMENT.id_lighting_level)
            OR  ISNULL(LIGHTING_LEVEL.id_lighting_level)
            OR  LIGHTING_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 Lighting_Level Assessment(s) do not have a valid Lighting_Level: ', GROUP_CONCAT(t_ASSESSMENT.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_Lighting_Level LIGHTING_LEVEL ON t_ASSESSMENT.id_lighting_level = LIGHTING_LEVEL.id_lighting_level
        WHERE 
                ISNULL(t_ASSESSMENT.id_lighting_level)
            OR  ISNULL(LIGHTING_LEVEL.id_lighting_level)
            OR  LIGHTING_LEVEL.active = 0
        ;
    END IF;
    -- id_location
    IF EXISTS (
        SELECT *
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_Location LOCATION ON t_ASSESSMENT.id_location = LOCATION.id_location
        WHERE 
                ISNULL(t_ASSESSMENT.id_location)
            OR  ISNULL(LOCATION.id_location)
            OR  LOCATION.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 Location Assessment(s) do not have a valid Location: ', GROUP_CONCAT(t_ASSESSMENT.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_Location LOCATION ON t_ASSESSMENT.id_location = LOCATION.id_location
        WHERE 
                ISNULL(t_ASSESSMENT.id_location)
            OR  ISNULL(LOCATION.id_location)
            OR  LOCATION.active = 0
        ;
    END IF;
    -- id_user_handler
    IF EXISTS (
        SELECT *
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_User USER_HANDLER ON t_ASSESSMENT.id_user_handler = USER_HANDLER.id_user
        WHERE 
                ISNULL(t_ASSESSMENT.id_user_handler)
            OR  ISNULL(USER_HANDLER.id_user)
            OR  USER_HANDLER.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 User_Handler Assessment(s) do not have a valid User_Handler: ', GROUP_CONCAT(t_ASSESSMENT.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Assessment t_ASSESSMENT
        LEFT JOIN fetchmetrics.DOG_User USER_HANDLER ON t_ASSESSMENT.id_user_handler = USER_HANDLER.id_user
        WHERE 
                ISNULL(t_ASSESSMENT.id_user_handler)
            OR  ISNULL(USER_HANDLER.id_user)
            OR  USER_HANDLER.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 Assessments.'
		)
        ;
    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;
	    END IF;

        DELETE FROM tmp_Assessment;
    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 ASSESSMENT
			INNER JOIN tmp_Assessment t_ASSESSMENT 
				ON  ASSESSMENT.id_assessment = t_ASSESSMENT.id_assessment
				AND t_ASSESSMENT.is_new = 0
			SET 
				  ASSESSMENT.id_weather = t_ASSESSMENT.id_weather
				, ASSESSMENT.id_lighting_level = t_ASSESSMENT.id_lighting_level
				, ASSESSMENT.id_location = t_ASSESSMENT.id_location
				, ASSESSMENT.id_user_handler = t_ASSESSMENT.id_user_handler
				, ASSESSMENT.temperature_celcius = t_ASSESSMENT.temperature_celcius
				, ASSESSMENT.difficulty_level = t_ASSESSMENT.difficulty_level
                , ASSESSMENT.notes = t_ASSESSMENT.notes
				, ASSESSMENT.active = t_ASSESSMENT.active
				, ASSESSMENT.id_change_set = v_id_change_set
			;
			
			INSERT INTO fetchmetrics.DOG_Assessment (
				  id_temp
                , id_weather
				, id_lighting_level
				, id_location
				, id_user_handler
				, temperature_celcius
				, difficulty_level
                , notes
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_ASSESSMENT.id_temp
                , t_ASSESSMENT.id_weather                     AS id_weather
				, t_ASSESSMENT.id_lighting_level                   AS id_lighting_level
				, t_ASSESSMENT.id_location     AS id_location
				, t_ASSESSMENT.id_user_handler     AS id_user_handler
				, t_ASSESSMENT.temperature_celcius     AS temperature_celcius
				, t_ASSESSMENT.difficulty_level     AS difficulty_level
                , t_ASSESSMENT.notes                       AS notes
				, t_ASSESSMENT.active                      AS active
				, a_id_user                                     AS created_by
				, v_time_start                                  AS created_on
			FROM tmp_Assessment t_ASSESSMENT
			WHERE 
				    t_ASSESSMENT.is_new = 1
				AND t_ASSESSMENT.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_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;
	END IF;

    DROP TEMPORARY TABLE tmp_Assessment;
    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_Assessment WHERE id_assessment > 740;
* /
delete
from fetchmetrics.DOG_Assessment_Audit
where id_assessment > 768
;
delete
from fetchmetrics.DOG_Assessment
where id_assessment > 768
;
delete
from fetchmetrics.DOG_Assessment_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Assessment_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment
;
select COUNT(*)
from fetchmetrics.DOG_Assessment
;

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

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


select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Assessment_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Assessment
;
select COUNT(*)
from fetchmetrics.DOG_Assessment
;

*/