
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Command;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Command;

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

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Command
BEFORE UPDATE ON parts.DOG_Command
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 parts.DOG_Command_Audit (
		  id_command
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_command_category
	SELECT NEW.id_command, 'id_command_category', CONVERT(OLD.id_command_category, CHAR), CONVERT(NEW.id_command_category, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_command_category <=> NEW.id_command_category)
	UNION
    -- Changed name
	SELECT NEW.id_command, 'name', OLD.name, NEW.name, NEW.id_change_set
		WHERE NOT OLD.name <=> NEW.name
	UNION
    -- Changed hand_signal_default_description
	SELECT NEW.id_command, 'hand_signal_default_description', OLD.hand_signal_default_description, NEW.hand_signal_default_description, NEW.id_change_set
		WHERE NOT OLD.hand_signal_default_description <=> NEW.hand_signal_default_description
	UNION
	-- Changed can_have_button
	SELECT NEW.id_command, 'can_have_button', CONVERT(CONVERT(OLD.can_have_button, SIGNED), CHAR), CONVERT(CONVERT(NEW.can_have_button, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.can_have_button <=> NEW.can_have_button)
	UNION
    -- Changed notes
	SELECT NEW.id_command, 'notes', OLD.notes, NEW.notes, NEW.id_change_set
		WHERE NOT OLD.notes <=> NEW.notes
	UNION
	-- Changed active
	SELECT NEW.id_command, '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 ;
