DROP PROCEDURE IF EXISTS PostMessage;
DELIMITER //
CREATE PROCEDURE PostMessage
(
  IN p_sid INT,
  IN p_password TEXT,
  IN p_did INT,
  IN p_text TEXT,
  OUT outputCode INT,
  OUT mid INT
)
MODIFIES SQL DATA
BEGIN
CALL `CheckIdLogin`(p_sid,p_password, outputCode);

IF outputCode = 42 THEN
	SET outputCode :=(
		SELECT
		(
			CASE 
				WHEN(
					SELECT
						COUNT(*)
					FROM
						discussions
					WHERE
						ID = p_did
				) = 1 THEN 2010
			ELSE 42
			END
		)
	);
	IF outputCode = 42 THEN
		SET @authorizedGroupID :=(SELECT authorizedGroupID FROM discussions WHERE ID=p_did);
		CALL `CheckInGroup`(p_sid, @authorizedGroupID, outputCode);
		
		IF outputCode = 42 THEN
			INSERT INTO messages(texte,senderID,sendTime,discussionID) VALUES (p_text,p_sid,NOW(),p_did);
			SET mid :=(SELECT LAST_INSERT_ID());
		END IF;
	END IF;
END IF;

END//
DELIMITER ;

