
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_save_dog;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_save_dog (
    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_access_level_view INT;
    DECLARE v_id_change_set INT;
    DECLARE v_id_permission_dog_edit 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_edit := (SELECT PERMISSION.id_permission FROM fetchmetrics.DOG_Permission PERMISSION WHERE PERMISSION.code = 'DOG_EDIT' 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);
    SET v_id_access_level_view := (SELECT ACCESS_LEVEL.id_access_level FROM fetchmetrics.DOG_Access_Level ACCESS_LEVEL WHERE ACCESS_LEVEL.code = 'VIEW' LIMIT 1);
    
    CALL fetchmetrics.p_core_validate_guid ( a_guid );
    
    DROP TABLE IF EXISTS tmp_Dog;
    
    CREATE TEMPORARY TABLE tmp_Dog (
          id_temp INT
        , id_dog INT
        , name VARCHAR(250)
        , appearance VARCHAR(1000)
        , mass_kg DECIMAL(7, 3)
        , 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_Dog (
		  id_temp
        , id_dog
        , name
        , appearance
        , mass_kg
        , notes
        , active
        , is_new
	)
    SELECT 
		  DOG_T.id_temp
		, COALESCE(DOG.id_dog, DOG_T.id_dog) AS id_dog
        , COALESCE(
              DOG_T.name
            , DOG.name
        ) AS name
        , COALESCE(
              DOG_T.appearance
            , DOG.appearance
        ) AS appearance
        , COALESCE(
              DOG_T.mass_kg
            , DOG.mass_kg
        ) AS mass_kg
        , COALESCE(
              DOG_T.notes
            , DOG.notes
        ) AS notes
        , COALESCE(DOG_T.active, 1) AS active
        , CASE WHEN IFNULL(DOG_T.id_dog, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM fetchmetrics.DOG_Dog_Temp DOG_T
    LEFT JOIN fetchmetrics.DOG_Dog DOG ON DOG_T.id_dog = DOG.id_dog
    WHERE DOG_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Dog_Temp records';
        SELECT * FROM tmp_Dog;
        SELECT COUNT(*) FROM tmp_Dog;
    END IF;

    -- Error names
    UPDATE tmp_Dog t_DOG
    SET t_DOG.name_error = COALESCE(t_DOG.code, t_DOG.name, t_DOG.id_dog, '(No Dog)')
    ;

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

    /*
    -- Missing Dog Ids
    UPDATE tmp_Dog t_DOG
    LEFT JOIN fetchmetrics.DOG_Dog DOG ON t_DOG.code = DOG.code
    SET 
        t_DOG.id_dog = DOG.id_dog
        , t_DOG.is_new = 0
    WHERE 
            IFNULL(t_DOG.id_dog, 0) < 1
        AND NOT ISNULL(DOG.id_dog)
    ;

    IF a_debug = 1 THEN
        SELECT 'After set missing id_dog';
        SELECT * FROM tmp_Dog;
        SELECT COUNT(*) FROM tmp_Dog;
    END IF;
    */

    -- Validation
    -- Missing mandatory fields
    -- name
    IF EXISTS ( SELECT * FROM tmp_Dog t_DOG WHERE t_DOG.name 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 Dog(s) do not have a valid Name: ', GROUP_CONCAT(t_DOG.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Dog t_DOG
        WHERE t_DOG.name IS NULL
        ;
    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_edit -- 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 Dogs.'
		)
        ;
    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_Dog;
	    END IF;

        DELETE FROM tmp_Dog;
    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_Dog DOG
			INNER JOIN tmp_Dog t_DOG 
				ON  DOG.id_dog = t_DOG.id_dog
				AND t_DOG.is_new = 0
			SET 
				  DOG.name = t_DOG.name
				, DOG.appearance = t_DOG.appearance
				, DOG.mass_kg = t_DOG.mass_kg
				, DOG.notes = t_DOG.notes
				, DOG.active = t_DOG.active
				, DOG.id_change_set = v_id_change_set
			;
			
            IF EXISTS (
                SELECT * 
                FROM tmp_Dog t_DOG
                WHERE 
                        t_DOG.is_new = 1
                    AND t_DOG.active = 1
                LIMIT 1
            ) THEN
                INSERT INTO fetchmetrics.DOG_Dog (
                      id_temp
                    , name
                    , appearance
                    , mass_kg
                    , notes
                    , active
                    , id_user_created_by
                    , created_on
                )
                SELECT
                      t_DOG.id_temp                    AS id_temp
                    , t_DOG.name                       AS name
                    , t_DOG.appearance                       AS appearance
                    , t_DOG.mass_kg                       AS mass_kg
                    , t_DOG.notes                       AS notes
                    , t_DOG.active                     AS active
                    , a_id_user                                     AS created_by
                    , v_time_start                                  AS created_on
                FROM tmp_Dog t_DOG
                WHERE 
                        t_DOG.is_new = 1
                    AND t_DOG.active = 1
                ;

                UPDATE tmp_Dog t_DOG
                INNER JOIN fetchmetrics.DOG_Dog DOG ON t_DOG.id_temp = DOG.id_temp
                SET t_DOG.id_dog = DOG.id_dog
                WHERE 
                        t_DOG.is_new = 1
                    AND t_DOG.active = 1
                ;
                
                INSERT INTO fetchmetrics.DOG_Dog_User_Link (
                      id_dog
                    , id_user
                    , id_access_level
                    , active
                    , id_user_created_by
                    , created_on
                )
                SELECT
                      t_DOG.id_dog
                    , a_id_user
                    , v_id_access_level_view
                    , 1 -- active
                    , a_id_user                                     AS created_by
                    , v_time_start                                  AS created_on
                FROM tmp_Dog t_DOG
                WHERE 
                        t_DOG.is_new = 1
                    AND t_DOG.active = 1
                ;
			END IF;
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM fetchmetrics.DOG_Dog_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_Dog;
	END IF;

    DROP TEMPORARY TABLE tmp_Dog;
    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_Dog_Audit WHERE id_dog > 740;
DELETE FROM fetchmetrics.DOG_Dog WHERE id_dog > 740;
* /
delete
from fetchmetrics.DOG_Dog_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Dog_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Dog_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Dog
;
select COUNT(*)
from fetchmetrics.DOG_Dog
;

INSERT INTO fetchmetrics.DOG_Dog_Temp (
      id_dog
    , code
    , name
    , active
    , guid
)
VALUES (
      -1 -- id_dog
    , 'ACTIVITIES' -- code
    , 'A Sport Is Fun' -- name
    , 1 -- active
    , 'ripplesipplenippletippledipplekipple'
);

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


select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Dog_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Dog_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Dog
;
select COUNT(*)
from fetchmetrics.DOG_Dog
;

*/