
USE fetchmetrics;

DROP TRIGGER IF EXISTS fetchmetrics.before_insert_DOG_Command_Button_Link;
DROP TRIGGER IF EXISTS fetchmetrics.before_update_DOG_Command_Button_Link;

DELIMITER //
CREATE TRIGGER fetchmetrics.before_insert_DOG_Command_Button_Link
BEFORE INSERT ON fetchmetrics.DOG_Command_Button_Link
FOR EACH ROW
BEGIN
	SET NEW.created_on := IFNULL(NEW.created_on, NOW());
END //
DELIMITER ;

DELIMITER //
CREATE TRIGGER fetchmetrics.before_update_DOG_Command_Button_Link
BEFORE UPDATE ON fetchmetrics.DOG_Command_Button_Link
FOR EACH ROW
BEGIN
	IF OLD.id_change_set <=> NEW.id_change_set THEN
		SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = 'New change Set ID must be provided.';
    END IF;
    
    INSERT INTO fetchmetrics.DOG_Command_Button_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_command
	SELECT NEW.id_link, 'id_command', CONVERT(OLD.id_command, CHAR), CONVERT(NEW.id_command, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_command <=> NEW.id_command)
	UNION
	-- Changed id_button_shape
	SELECT NEW.id_link, 'id_button_shape', CONVERT(OLD.id_button_shape, CHAR), CONVERT(NEW.id_button_shape, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_button_shape <=> NEW.id_button_shape)
	UNION
	-- Changed id_button_colour
	SELECT NEW.id_link, 'id_button_colour', CONVERT(OLD.id_button_colour, CHAR), CONVERT(NEW.id_button_colour, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_button_colour <=> NEW.id_button_colour)
	UNION
	-- Changed id_button_icon
	SELECT NEW.id_link, 'id_button_icon', CONVERT(OLD.id_button_icon, CHAR), CONVERT(NEW.id_button_icon, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_button_icon <=> NEW.id_button_icon)
	UNION
	-- Changed id_location
	SELECT NEW.id_link, 'id_location', CONVERT(OLD.id_location, CHAR), CONVERT(NEW.id_location, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_location <=> NEW.id_location)
	UNION
	-- Changed active
	SELECT NEW.id_link, 'active', CONVERT(CONVERT(OLD.active, SIGNED), CHAR), CONVERT(CONVERT(NEW.active, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.active <=> NEW.active)
    ;
END //
DELIMITER ;
