DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`mail_new`(
	 vMessageId VARCHAR(100)
	,vSender VARCHAR(150)
    ,OUT vSelf INT
)
BEGIN
/**
 * Registers a mail message.
 *
 * @param vMessageId Message-ID of email
 * @param vSender Id of mail sender
 * @param vSelf The created message id
 */
	DECLARE vSenderId INT;
	DECLARE vIsDuplicated BOOL;
	DECLARE duplicateKey CONDITION FOR 1062;

	DECLARE CONTINUE HANDLER FOR duplicateKey
		SET vIsDuplicated = TRUE;

	SELECT id INTO vSenderId
		FROM mailSender
		WHERE mail = vSender;

	SET vIsDuplicated = FALSE;
	INSERT INTO mail SET
		sender = vSender,
		senderFk = vSenderId,
		messageId = vMessageId;
		
	IF vIsDuplicated THEN
		SELECT id INTO vSelf
			FROM mail
			WHERE messageId = vMessageId;
	ELSE
		SET vSelf = LAST_INSERT_ID();
	END IF;
END$$
DELIMITER ;
