DROP PROCEDURE IF EXISTS DeleteMessage;
DELIMITER //
CREATE PROCEDURE DeleteMessage
(
  IN p_sid INT,
  IN p_password TEXT,
  IN p_mid INT,
  OUT outputCode INT,
  OUT did INT
)
MODIFIES SQL DATA
BEGIN

CALL `CheckIdLogin`(p_sid,p_password, outputCode);

IF outputCode = 42 THEN
	SET outputCode :=(
		SELECT
		(
			CASE 
				WHEN(
					SELECT
						COUNT(*)
					FROM
						messages
					WHERE
						ID = p_mid
				) = 1 THEN 2010
			ELSE 42
			END
		)
	);
	IF outputCode = 42 THEN
		SET did :=(SELECT discussionID FROM messages WHERE ID = p_mid);
		SET @authorizedGroupID :=(SELECT authorizedGroupID FROM discussions WHERE ID=did);
		CALL `CheckInGroup`(p_sid, @authorizedGroupID, outputCode);
		
		IF outputCode = 42 THEN
			DELETE FROM messages WHERE ID = p_mid;
		END IF;
	END IF;
END IF;

END//
DELIMITER ;

