
USE fetchmetrics;

DROP PROCEDURE IF EXISTS fetchmetrics.p_dog_save_company;

DELIMITER //
CREATE PROCEDURE fetchmetrics.p_dog_save_company (
    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_company_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_company_edit := (SELECT PERMISSION.id_permission FROM fetchmetrics.DOG_Permission PERMISSION WHERE PERMISSION.code = 'COMPANY_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_Company_Copy;
    DROP TABLE IF EXISTS tmp_Company;
    
    CREATE TEMPORARY TABLE tmp_Company (
          id_temp INT
        , id_company INT
        , name VARCHAR(1000)
        , website TEXT
        , active BIT
        , is_new BIT
        , name_error VARCHAR(250)
    );

    CREATE TEMPORARY TABLE tmp_Company_Copy (
          id_temp INT
        , id_company INT
        , name VARCHAR(1000)
        , website 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_Company (
		  id_temp
        , id_company
        , name
        , website
        , active
        , is_new
	)
    SELECT 
		  COMPANY_T.id_temp
		, COALESCE(COMPANY.id_company, COMPANY_T.id_company) AS id_company
        , COALESCE(
              COMPANY_T.name
            , COMPANY.name
        ) AS name
        , COALESCE(
              COMPANY_T.website
            , COMPANY.website
        ) AS website
        , COALESCE(COMPANY_T.active, 1) AS active
        , CASE WHEN IFNULL(COMPANY_T.id_company, 0) < 1 THEN 1 ELSE 0 END AS is_new
	FROM fetchmetrics.DOG_Company_Temp COMPANY_T
    LEFT JOIN fetchmetrics.DOG_Company COMPANY 
        ON  COMPANY_T.id_company = COMPANY.id_company
        OR  (
                COMPANY_T.website = COMPANY.website
            AND COMPANY_T.name = COMPANY.name
        )
    WHERE COMPANY_T.guid = a_guid
    ;

    IF a_debug = 1 THEN
        SELECT 'Company_Temp records';
        SELECT * FROM tmp_Company;
        SELECT COUNT(*) FROM tmp_Company;
    END IF;

    -- Error names
    UPDATE tmp_Company t_COMPANY
    SET t_COMPANY.name_error = COALESCE(t_COMPANY.website, t_COMPANY.name, t_COMPANY.id_company, '(No Company)')
    ;

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

    -- Validation
    -- Missing mandatory fields
    -- website
    IF EXISTS ( SELECT * FROM tmp_Company t_COMPANY WHERE t_COMPANY.website 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 Company(s) do not have a valid Website: ', GROUP_CONCAT(t_COMPANY.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Company t_COMPANY
        WHERE t_COMPANY.website IS NULL
        ;
    END IF;
    -- name
    IF EXISTS ( SELECT * FROM tmp_Company t_COMPANY WHERE t_COMPANY.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 Company(s) do not have a valid Name: ', GROUP_CONCAT(t_COMPANY.name_error SEPARATOR ', ')) AS msg
        FROM tmp_Company t_COMPANY
        WHERE t_COMPANY.name IS NULL
        ;
    END IF;

    -- Duplicates
    INSERT INTO tmp_Company_Copy (
		  id_temp
        , id_company
        , website
        , name
        , active
        , is_new
        , name_error
    )
    SELECT 
          t_COMPANY.id_temp
        , t_COMPANY.id_company
        , t_COMPANY.website
        , t_COMPANY.name
        , t_COMPANY.active
        , t_COMPANY.is_new
        , t_COMPANY.name_error
    FROM tmp_Company t_COMPANY
    ;

    IF a_debug = 1 THEN
        SELECT COUNT(*) AS Count_Temp_Company FROM tmp_Company;
        SELECT COUNT(*) AS Count_Temp_Company_Copy FROM tmp_Company_Copy;

        WITH 
              Combined_Company AS (
                SELECT 
                      COMPANY.id_company
                    , COMPANY.website
                    , COMPANY.name
                    , COALESCE(t_COMPANY_COPY.website, t_COMPANY_COPY.name, t_COMPANY_COPY.id_company, '(No Company)') AS name_error
                FROM fetchmetrics.DOG_Company COMPANY
                LEFT JOIN tmp_Company_Copy t_COMPANY_COPY 
                    ON  COMPANY.website = t_COMPANY_COPY.website
                    OR COMPANY.name = t_COMPANY_COPY.name
                WHERE t_COMPANY_COPY.is_new = 1
                UNION
                SELECT 
                      t_COMPANY.id_company
                    , t_COMPANY.website
                    , t_COMPANY.name
                    , t_COMPANY.name_error
                FROM tmp_Company t_COMPANY
            )
            , Duplicate_Company_Row_Numbers AS (
                SELECT 
                      COMBINED_COMPANY.id_company
                    , COMBINED_COMPANY.website
                    , COMBINED_COMPANY.name
                    , COMBINED_COMPANY.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_COMPANY.website ORDER BY COMBINED_COMPANY.name_error ASC) AS index_company_as_duplicate
                FROM Combined_Company COMBINED_COMPANY
            )
        SELECT *
        FROM Duplicate_Company_Row_Numbers;
    END IF;
    
    IF EXISTS (
        WITH 
              Combined_Company AS (
                SELECT 
                      COMPANY.id_company
                    , COMPANY.website
                    , COMPANY.name
                    , COALESCE(t_COMPANY_COPY.website, t_COMPANY_COPY.name, t_COMPANY_COPY.id_company, '(No Company)') AS name_error
                FROM fetchmetrics.DOG_Company COMPANY
                LEFT JOIN tmp_Company_Copy t_COMPANY_COPY 
                    ON  COMPANY.website = t_COMPANY_COPY.website
                    OR COMPANY.name = t_COMPANY_COPY.name
                WHERE t_COMPANY_COPY.is_new = 1
                UNION
                SELECT 
                      t_COMPANY.id_company
                    , t_COMPANY.website
                    , t_COMPANY.name
                    , t_COMPANY.name_error
                FROM tmp_Company t_COMPANY
            )
            , Duplicate_Company_Row_Numbers AS (
                SELECT 
                      COMBINED_COMPANY.id_company
                    , COMBINED_COMPANY.website
                    , COMBINED_COMPANY.name
                    , COMBINED_COMPANY.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_COMPANY.website ORDER BY COMBINED_COMPANY.name_error ASC) AS index_company_as_duplicate
                FROM Combined_Company COMBINED_COMPANY
            )
        SELECT *
        FROM Duplicate_Company_Row_Numbers DUPLICATE_COMPANY
        WHERE DUPLICATE_COMPANY.index_company_as_duplicate > 1
        GROUP BY DUPLICATE_COMPANY.website
    ) THEN
        INSERT INTO tmp_Msg_Error (
              id_type
            , code
            , msg
        )
        WITH 
              Combined_Company AS (
                SELECT 
                      COMPANY.id_company
                    , COMPANY.website
                    , COMPANY.name
                    , COALESCE(t_COMPANY_COPY.website, t_COMPANY_COPY.name, t_COMPANY_COPY.id_company, '(No Company)') AS name_error
                FROM fetchmetrics.DOG_Company COMPANY
                LEFT JOIN tmp_Company_Copy t_COMPANY_COPY 
                    ON  COMPANY.website = t_COMPANY_COPY.website
                    OR COMPANY.name = t_COMPANY_COPY.name
                WHERE t_COMPANY_COPY.is_new = 1
                UNION
                SELECT 
                      t_COMPANY.id_company
                    , t_COMPANY.website
                    , t_COMPANY.name
                    , t_COMPANY.name_error
                FROM tmp_Company t_COMPANY
            )
            , Duplicate_Company_Row_Numbers AS (
                SELECT 
                      COMBINED_COMPANY.id_company
                    , COMBINED_COMPANY.website
                    , COMBINED_COMPANY.name
                    , COMBINED_COMPANY.name_error
                    , ROW_NUMBER() OVER (PARTITION BY COMBINED_COMPANY.website ORDER BY COMBINED_COMPANY.name_error ASC) AS index_company_as_duplicate
                FROM Combined_Company COMBINED_COMPANY
            )
        SELECT
              v_id_type_error_bad_data
            , v_code_type_error_bad_data
            , CONCAT('Attempt to create duplicate or overwrite existing Command Categories on: ', GROUP_CONCAT(DUPLICATE_COMPANY.name_error SEPARATOR ', ')) AS msg
        FROM Duplicate_Company_Row_Numbers DUPLICATE_COMPANY
        WHERE DUPLICATE_COMPANY.index_company_as_duplicate > 1
        GROUP BY DUPLICATE_COMPANY.website
        ;
    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_company_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 Commands.'
		)
        ;
    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_Company;
	    END IF;

        DELETE FROM tmp_Company;
    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_Company COMPANY
			INNER JOIN tmp_Company t_COMPANY 
				ON  COMPANY.id_company = t_COMPANY.id_company
				AND t_COMPANY.is_new = 0
			SET 
				  COMPANY.website = t_COMPANY.website
				, COMPANY.name = t_COMPANY.name
				, COMPANY.active = t_COMPANY.active
				, COMPANY.id_change_set = v_id_change_set
			;
			
            IF EXISTS (
                SELECT * 
                FROM tmp_Company t_COMPANY
                WHERE 
                        t_COMPANY.is_new = 1
                    AND t_COMPANY.active = 1
                LIMIT 1
            ) THEN
                INSERT INTO fetchmetrics.DOG_Company (
                      id_temp
                    , website
                    , name
                    , active
                    , id_user_created_by
                    , created_on
                )
                SELECT
                      t_COMPANY.id_temp                    AS id_temp
                    , t_COMPANY.website                       AS website
                    , t_COMPANY.name                       AS name
                    , t_COMPANY.active                     AS active
                    , a_id_user                                     AS created_by
                    , v_time_start                                  AS created_on
                FROM tmp_Company t_COMPANY
                WHERE 
                        t_COMPANY.is_new = 1
                    AND t_COMPANY.active = 1
                ;

                UPDATE tmp_Company t_COMPANY
                INNER JOIN fetchmetrics.DOG_Company COMPANY ON t_COMPANY.id_temp = COMPANY.id_temp
                SET t_COMPANY.id_company = COMPANY.id_company
                WHERE 
                        t_COMPANY.is_new = 1
                    AND t_COMPANY.active = 1
                ;
                
                INSERT INTO fetchmetrics.DOG_Company_User_Link (
                      id_company
                    , id_user
                    , id_access_level
                    , active
                    , id_user_created_by
                    , created_on
                )
                SELECT
                      t_COMPANY.id_company
                    , a_id_user
                    , v_id_access_level_view
                    , 1 -- active
                    , a_id_user                                     AS created_by
                    , v_time_start                                  AS created_on
                FROM tmp_Company t_COMPANY
                WHERE 
                        t_COMPANY.is_new = 1
                    AND t_COMPANY.active = 1
                ;
			END IF;
		COMMIT;
    END IF;
	
	START TRANSACTION;

		DELETE FROM fetchmetrics.DOG_Company_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_Company;
	END IF;

    DROP TEMPORARY TABLE tmp_Company_Copy;
    DROP TEMPORARY TABLE tmp_Company;
    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_Company_Audit WHERE id_company > 740;
DELETE FROM fetchmetrics.DOG_Company WHERE id_company > 740;
* /
delete
from fetchmetrics.DOG_Company_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Company_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Company_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Company
;
select COUNT(*)
from fetchmetrics.DOG_Company
;

INSERT INTO fetchmetrics.DOG_Company_Temp (
      id_company
    , website
    , name
    , active
    , guid
)
VALUES (
      -1 -- id_company
    , 'ACTIVITIES' -- website
    , 'A Sport Is Fun' -- name
    , 1 -- active
    , 'ripplesipplenippletippledipplekipple'
);

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


select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Company_Temp
;
select COUNT(*)
from fetchmetrics.DOG_Company_Temp
;
select 
	*
    -- COUNT(*)
-- delete
from fetchmetrics.DOG_Company
;
select COUNT(*)
from fetchmetrics.DOG_Company
;

*/