
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_save_location;

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

		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_Location_Copy;
    DROP TABLE IF EXISTS tmp_Location;
    
    CREATE TEMPORARY TABLE tmp_Location (
          id_temp INT
        , id_location INT
        , id_location_parent INT
        , code VARCHAR(250)
        , name VARCHAR(250)
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)
    );

    CREATE TEMPORARY TABLE tmp_Location_Copy (
          id_temp INT
        , id_location INT
        , id_location_parent INT
        , code VARCHAR(250)
        , name VARCHAR(250)
        , 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_Location (
		  id_temp
        , id_location
        , id_location_parent
        , code
        , name
        , active
        , is_new
	)
    SELECT 
		  LOCATIONS_T.id_temp
		, COALESCE(
              LOCATIONS.id_location
            , LOCATIONS_T.id_location
        ) AS id_location
        , CASE WHEN IFNULL(LOCATIONS_T.id_location_parent, 0) < 1 THEN NULL ELSE LOCATIONS_T.id_location_parent END AS id_location_parent
        , COALESCE(
              LOCATIONS_T.code
            , LOCATIONS.code
        ) AS code
        , COALESCE(
              LOCATIONS_T.name
            , LOCATIONS.name
        ) AS name
        , COALESCE(LOCATIONS_T.active, 1) AS active
        , CASE WHEN COALESCE(LOCATIONS.id_location, LOCATIONS_T.id_location, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM fetchmetrics.DOG_Location_Temp LOCATIONS_T
    LEFT JOIN fetchmetrics.DOG_Location LOCATIONS 
        ON  LOCATIONS_T.id_location = LOCATIONS.id_location
        OR  (
                LOCATIONS_T.id_location_parent = LOCATIONS.id_location_parent
            AND LOCATIONS_T.name = LOCATIONS.name
        )
    WHERE LOCATIONS_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Location_Temp records';
        SELECT * FROM tmp_Location;
        SELECT COUNT(*) FROM tmp_Location;
    END IF;

    -- Error names
    UPDATE tmp_Location t_LOCATIONS
    LEFT JOIN fetchmetrics.DOG_Location LOCATIONS_PARENT ON t_LOCATIONS.id_location_parent = LOCATIONS_PARENT.id_location
    SET t_LOCATIONS.name_error = CONCAT(
          COALESCE(LOCATIONS_PARENT.name, t_LOCATIONS.id_location_parent, '(No Parent Location)')
        , ' - '
        , COALESCE(t_LOCATIONS.name, t_LOCATIONS.code, t_LOCATIONS.id_location, '(No Location)')
    )
    ;

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

    -- Validation
    -- Missing mandatory fields
    -- code
    IF EXISTS ( SELECT * FROM tmp_Location t_LOCATIONS WHERE t_LOCATIONS.code 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 Location(s) do not have a valid Code: ', GROUP_CONCAT(t_LOCATIONS.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Location t_LOCATIONS
        WHERE t_LOCATIONS.code IS NULL
        ;
    END IF;
    -- name
    IF EXISTS ( SELECT * FROM tmp_Location t_LOCATIONS WHERE t_LOCATIONS.name IS NULL ) THEN
        INSERT INTO tmp_Msg_Error (
            id_type
            , name
            , msg
        )
        SELECT
            v_id_type_error_bad_data
            , v_name_type_error_bad_data
            , CONCAT('The following Location(s) do not have a valid Name: ', GROUP_CONCAT(t_LOCATIONS.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Location t_LOCATIONS
        WHERE t_LOCATIONS.name IS NULL
        ;
    END IF;

    -- Duplicates
    -- Duplicate names
    INSERT INTO tmp_Location_Copy (
        id_temp
        , id_location
        , id_location_parent
        , code
        , name
        , active
        , is_new
        , name_error
    )
    SELECT 
          t_LOCATIONS.id_temp
        , t_LOCATIONS.id_location
        , t_LOCATIONS.id_location_parent
        , t_LOCATIONS.code
        , t_LOCATIONS.name
        , t_LOCATIONS.active
        , t_LOCATIONS.is_new
        , t_LOCATIONS.name_error
    FROM tmp_Location t_LOCATIONS
    ;

    IF a_debug = 1 THEN
        SELECT COUNT(*) AS Count_Temp_Location FROM tmp_Location;
        SELECT COUNT(*) AS Count_Temp_Location_Copy FROM tmp_Location_Copy;

        WITH 
              Combined_Locations AS (
                SELECT 
                      LOCATIONS.id_location
                    , LOCATIONS.id_location_parent
                    , LOCATIONS.code
                    , LOCATIONS.name
                    , CONCAT(
                        COALESCE(LOCATIONS_PARENT.name, t_LOCATIONS_COPY.id_location_parent, '(No Parent Location)')
                        , ' - '
                        , COALESCE(t_LOCATIONS_COPY.name, t_LOCATIONS_COPY.code, t_LOCATIONS_COPY.id_location, '(No Location)')
                    ) AS name_error
                FROM fetchmetrics.DOG_Location LOCATIONS 
                LEFT JOIN tmp_Location_Copy t_LOCATIONS_COPY ON LOCATIONS.name = t_LOCATIONS_COPY.name
                LEFT JOIN fetchmetrics.DOG_Location LOCATIONS_PARENT ON LOCATIONS.id_location = LOCATIONS_PARENT.id_location_parent
                WHERE t_LOCATIONS_COPY.is_new = 1
                UNION
                SELECT 
                      t_LOCATIONS.id_location
                    , t_LOCATIONS.id_location_parent
                    , t_LOCATIONS.code
                    , t_LOCATIONS.name
                    , t_LOCATIONS.name_error
                FROM tmp_Location t_LOCATIONS
            )
            , Duplicate_Location_Name_Row_Numbers AS (
                SELECT 
                      COMBINED_LOCATIONS.id_location
                    , COMBINED_LOCATIONS.id_location_parent
                    , COMBINED_LOCATIONS.code
                    , COMBINED_LOCATIONS.name
                    , COMBINED_LOCATIONS.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_LOCATIONS.name ORDER BY COMBINED_LOCATIONS.name_error ASC) AS index_location_name_as_duplicate
                FROM Combined_Locations COMBINED_LOCATIONS
            )
        SELECT *
        FROM Duplicate_Location_Name_Row_Numbers
        ;
    END IF;
    
    IF EXISTS (
        WITH 
              Combined_Locations AS (
                SELECT 
                      LOCATIONS.id_location
                    , LOCATIONS.id_location_parent
                    , LOCATIONS.code
                    , LOCATIONS.name
                    , CONCAT(
                        COALESCE(LOCATIONS_PARENT.name, t_LOCATIONS_COPY.id_location_parent, '(No Parent Location)')
                        , ' - '
                        , COALESCE(t_LOCATIONS_COPY.name, t_LOCATIONS_COPY.code, t_LOCATIONS_COPY.id_location, '(No Location)')
                    ) AS name_error
                FROM fetchmetrics.DOG_Location LOCATIONS 
                LEFT JOIN tmp_Location_Copy t_LOCATIONS_COPY ON LOCATIONS.name = t_LOCATIONS_COPY.name
                LEFT JOIN fetchmetrics.DOG_Location LOCATIONS_PARENT ON LOCATIONS.id_location = LOCATIONS_PARENT.id_location_parent
                WHERE t_LOCATIONS_COPY.is_new = 1
                UNION
                SELECT 
                      t_LOCATIONS.id_location
                    , t_LOCATIONS.id_location_parent
                    , t_LOCATIONS.code
                    , t_LOCATIONS.name
                    , t_LOCATIONS.name_error
                FROM tmp_Location t_LOCATIONS
            )
            , Duplicate_Location_Name_Row_Numbers AS (
                SELECT 
                      COMBINED_LOCATIONS.id_location
                    , COMBINED_LOCATIONS.id_location_parent
                    , COMBINED_LOCATIONS.code
                    , COMBINED_LOCATIONS.name
                    , COMBINED_LOCATIONS.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_LOCATIONS.name ORDER BY COMBINED_LOCATIONS.name_error ASC) AS index_location_name_as_duplicate
                FROM Combined_Locations COMBINED_LOCATIONS
            )
        SELECT *
        FROM Duplicate_Location_Name_Row_Numbers DUPLICATE_LOCATIONS
        WHERE DUPLICATE_LOCATIONS.index_location_name_as_duplicate > 1
        GROUP BY DUPLICATE_LOCATIONS.name
    ) THEN
        INSERT INTO tmp_Msg_Error (
              id_type
            , code
            , msg
        )
        WITH 
              Combined_Locations AS (
                SELECT 
                      LOCATIONS.id_location
                    , LOCATIONS.id_location_parent
                    , LOCATIONS.code
                    , LOCATIONS.name
                    , CONCAT(
                        COALESCE(LOCATIONS_PARENT.name, t_LOCATIONS_COPY.id_location_parent, '(No Parent Location)')
                        , ' - '
                        , COALESCE(t_LOCATIONS_COPY.name, t_LOCATIONS_COPY.code, t_LOCATIONS_COPY.id_location, '(No Location)')
                    ) AS name_error
                FROM fetchmetrics.DOG_Location LOCATIONS 
                LEFT JOIN tmp_Location_Copy t_LOCATIONS_COPY ON LOCATIONS.name = t_LOCATIONS_COPY.name
                LEFT JOIN fetchmetrics.DOG_Location LOCATIONS_PARENT ON LOCATIONS.id_location = LOCATIONS_PARENT.id_location_parent
                WHERE t_LOCATIONS_COPY.is_new = 1
                UNION
                SELECT 
                      t_LOCATIONS.id_location
                    , t_LOCATIONS.id_location_parent
                    , t_LOCATIONS.code
                    , t_LOCATIONS.name
                    , t_LOCATIONS.name_error
                FROM tmp_Location t_LOCATIONS
            )
            , Duplicate_Location_Name_Row_Numbers AS (
                SELECT 
                      COMBINED_LOCATIONS.id_location
                    , COMBINED_LOCATIONS.id_location_parent
                    , COMBINED_LOCATIONS.code
                    , COMBINED_LOCATIONS.name
                    , COMBINED_LOCATIONS.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_LOCATIONS.name ORDER BY COMBINED_LOCATIONS.name_error ASC) AS index_location_name_as_duplicate
                FROM Combined_Locations COMBINED_LOCATIONS
            )
        SELECT
              v_id_type_error_bad_data
            , v_code_type_error_bad_data
            , CONCAT('Attempt to create duplicate or overwrite existing Locations on: ', GROUP_CONCAT(DUPLICATE_LOCATIONS.name_error SEPARATOR ', ')) AS msg
        FROM Duplicate_Location_Name_Row_Numbers DUPLICATE_LOCATIONS
        WHERE DUPLICATE_LOCATIONS.index_location_as_duplicate > 1
        GROUP BY DUPLICATE_LOCATIONS.name
        ;
    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 Locations.'
		)
        ;
    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_Location;
	    END IF;

        DELETE FROM tmp_Location;
    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_Location LOCATIONS
			INNER JOIN tmp_Location t_LOCATIONS 
				ON  LOCATIONS.id_location = t_LOCATIONS.id_location
				AND t_LOCATIONS.is_new = 0
			SET 
				  LOCATIONS.id_location_parent = t_LOCATIONS.id_location_parent
				, LOCATIONS.code = t_LOCATIONS.code
				, LOCATIONS.name = t_LOCATIONS.name
				, LOCATIONS.active = t_LOCATIONS.active
				, LOCATIONS.id_change_set = v_id_change_set
			;
			
			INSERT INTO fetchmetrics.DOG_Location (
				  id_location_parent
				, code
				, name
				, active
				, id_user_created_by
				, created_on
			)
			SELECT
				  t_LOCATIONS.id_location_parent                     AS id_location_parent
				, t_LOCATIONS.code                      AS code
				, t_LOCATIONS.name                      AS name
				, t_LOCATIONS.active                      AS active
				, a_id_user                                     AS created_by
				, v_time_start                                  AS created_on
			FROM tmp_Location t_LOCATIONS
			WHERE 
				    t_LOCATIONS.is_new = 1
				AND t_LOCATIONS.active = 1
			;
			
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM fetchmetrics.DOG_Location_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_Location;
	END IF;

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



/*

'ripplesipplenippletippledipplekippsy'
DELETE FROM fetchmetrics.DOG_Location WHERE id_location > 740;
* /
delete
from fetchmetrics.DOG_Location_Audit
where id_location > 768
;
delete
from fetchmetrics.DOG_Location
where id_location > 768
;
delete
from fetchmetrics.DOG_Location_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Location_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Location_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Location
;
select COUNT(*)
from fetchmetrics.DOG_Location
;

INSERT INTO fetchmetrics.DOG_Location_Temp (
      id_location
    , id_location_parent
    , code
    , name
    , active
    , guid
)
VALUES (
      -1 -- id_location
    , 1 -- id_location_parent
    , 'HOME' -- code
    , 'Home' -- name
    , 1 -- active
    , 'ripplesipplenippletippledipplekippsy'
);

CALL fetchmetrics.p_dog_save_location (
	'nipples'
    , 'ripplesipplenippletippledipplekippsy'
    , 1
    , 1
);


select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Location_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Location_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Location
;
select COUNT(*)
from fetchmetrics.DOG_Location
;

*/