DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `psico`.`examNew`(vFellow VARCHAR(50), vType INT, vQuestionsNumber INT, OUT vExamFk INT)
BEGIN

	DECLARE done BOOL DEFAULT FALSE;
    DECLARE vFellowFk INT;
	DECLARE vQuestionFk INT;

	DECLARE rs CURSOR FOR
			SELECT q.id 
				FROM psico.question  q
					LEFT JOIN psico.questionType qt ON q.id = qt.questionFk 
				WHERE qt.examTypeFk = vType
			ORDER BY randomOrder;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
    
    IF vQuestionsNumber = 0 THEN
    
		SET vQuestionsNumber = 30;
        
	END IF;
    
	CALL psico.answerSort();
    
    CALL psico.questionSort();

	INSERT INTO psico.fellow(name) VALUES(vFellow);
    
    SELECT MAX(id) INTO vFellowFk FROM psico.fellow;
    
    INSERT INTO psico.exam(fellowFk, started, questionsCount,examTypeFk) VALUES(vFellowFk, util.VN_NOW(), vQuestionsNumber,vType);
    
    SELECT MAX(id) INTO vExamFk FROM psico.exam;

	OPEN rs;

	FETCH rs INTO vQuestionFk;

	WHILE NOT done AND vQuestionsNumber DO
    
		INSERT INTO psico.examQuestion(examFk, questionFk)
			VALUES (vExamFk, vQuestionFk);
	
		
        FETCH rs INTO vQuestionFk;
        
        SET vQuestionsNumber = vQuestionsNumber - 1;

	END WHILE;

	CLOSE rs;

	
END$$
DELIMITER ;
