DELIMITER $$
CREATE OR REPLACE DEFINER=`vn`@`localhost` PROCEDURE `vn`.`mail_insert`(
	vReceiver VARCHAR(255),
	vReplyTo VARCHAR(50),
	vSubject VARCHAR(100),
	vBody TEXT)
BEGIN
/**
 * Inserta en la tabla vn.mail
 *
 * @param vReceiver Receptor del correo 
 * @param vReplyTo A quién contestar el correo
 * @param vSubject Título del correo
 * @param vBody Cuerpo del correo
 */
	
	DECLARE vIsRepeated BOOLEAN;

	SELECT COUNT(*) INTO vIsRepeated
		FROM vn.mail
		WHERE creationDate >= util.VN_CURDATE()
			AND `receiver` = vReceiver
			AND `replyTo` = vReplyTo
			AND `subject` = vSubject
			AND !sent;

	IF NOT vIsRepeated THEN

		INSERT INTO vn.mail SET
				`receiver` = vReceiver,
				`replyTo` = vReplyTo,
				`subject` = vSubject,
				`body` = IFNULL(vBody,vSubject);

	END IF;

END$$
DELIMITER ;
