
USE parts;

DROP TRIGGER IF EXISTS parts.before_insert_DOG_Dog_Command_Link;
DROP TRIGGER IF EXISTS parts.before_update_DOG_Dog_Command_Link;

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

DELIMITER //
CREATE TRIGGER parts.before_update_DOG_Dog_Command_Link
BEFORE UPDATE ON parts.DOG_Dog_Command_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 parts.DOG_Dog_Command_Link_Audit (
		  id_link
        , name_field
        , value_prev
        , value_new
        , id_change_set
    )
	-- Changed id_dog
	SELECT NEW.id_link, 'id_dog', CONVERT(OLD.id_dog, CHAR), CONVERT(NEW.id_dog, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_dog <=> NEW.id_dog)
	UNION
	-- 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_understanding_level
	SELECT NEW.id_link, 'id_understanding_level', CONVERT(OLD.id_understanding_level, CHAR), CONVERT(NEW.id_understanding_level, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_understanding_level <=> NEW.id_understanding_level)
	UNION
	-- Changed id_obedience_level
	SELECT NEW.id_link, 'id_obedience_level', CONVERT(OLD.id_obedience_level, CHAR), CONVERT(NEW.id_obedience_level, CHAR), NEW.id_change_set
		WHERE NOT (OLD.id_obedience_level <=> NEW.id_obedience_level)
	UNION
    -- Changed hand_signal_description
	SELECT NEW.id_link, 'hand_signal_description', OLD.hand_signal_description, NEW.hand_signal_description, NEW.id_change_set
		WHERE NOT OLD.hand_signal_description <=> NEW.hand_signal_description
	UNION
    -- Changed notes
	SELECT NEW.id_link, 'notes', OLD.notes, NEW.notes, NEW.id_change_set
		WHERE NOT OLD.notes <=> NEW.notes
	UNION
    /*
	-- Changed has_button
	SELECT NEW.id_link, 'has_button', CONVERT(CONVERT(OLD.has_button, SIGNED), CHAR), CONVERT(CONVERT(NEW.has_button, SIGNED), CHAR), NEW.id_change_set
		WHERE NOT (OLD.has_button <=> NEW.has_button)
	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 ;
