
USE fetchmetrics;

DROP TRIGGER IF EXISTS fetchmetrics.before_insert_DOG_Button_Icon;
DROP TRIGGER IF EXISTS fetchmetrics.before_update_DOG_Button_Icon;

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

DELIMITER //
CREATE TRIGGER fetchmetrics.before_update_DOG_Button_Icon
BEFORE UPDATE ON fetchmetrics.DOG_Button_Icon
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_Button_Icon_Audit (
		  id_button_icon
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_image
	SELECT NEW.id_button_icon, 'id_image', CONVERT(OLD.id_image, CHAR), CONVERT(NEW.id_image, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_image <=> NEW.id_image)
	UNION
	-- Changed code
	SELECT NEW.id_button_icon, 'code', OLD.code, NEW.code, NEW.id_change_set
		WHERE NOT (OLD.code <=> NEW.code)
	UNION
	-- Changed name
	SELECT NEW.id_button_icon, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT (OLD.name <=> NEW.name)
	UNION
	-- Changed notes
	SELECT NEW.id_button_icon, 'notes', OLD.notes, NEW.notes, NEW.id_change_set
		WHERE NOT (OLD.notes <=> NEW.notes)
	UNION
	-- Changed active
	SELECT NEW.id_button_icon, '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 ;
