DELIMITER $$
CREATE OR REPLACE DEFINER=`vn-admin`@`localhost` EVENT `vn`.`printQueue_check`
	ON SCHEDULE EVERY 10 MINUTE
		STARTS '2022-01-28 09:52:46.000'
	ON COMPLETION PRESERVE
	ENABLE
DO BEGIN

	DECLARE vCurrentCount INT;
	DECLARE vCheckSum INT;
	DECLARE vIsAlreadyNotified BOOLEAN;
	DECLARE vTableQueue TEXT;
	DECLARE vLineQueue TEXT;
	DECLARE vDone BOOL DEFAULT FALSE;
	DECLARE vPrintQueueLimit INT;

	DECLARE vCur CURSOR FOR
		SELECT CONCAT('<tr>\n\t\t\t\t\t\t\t<td>', IFNULL(pq.id, ''), '</td>\n\t\t\t\t\t\t\t<td>', IFNULL(p.path, ''),'</td>\n\t\t\t\t\t\t\t<td>', IFNULL(r.name, ''),'</td>\n\t\t\t\t\t\t\t<td>', IFNULL(pq.statusCode, ''),'</td>\n\t\t\t\t\t\t\t<td>', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),'</td>\n\t\t\t\t\t\t\t<td>', IFNULL(pq.`error`, ''),'</td>\n\t\t\t\t\t\t</tr>')
			FROM printQueue pq
				LEFT JOIN worker w ON w.id = pq.workerFk
				LEFT JOIN printer p ON p.id = pq.printerFk
				LEFT JOIN report r ON r.id = pq.reportFk
				JOIN printQueueConfig
			LIMIT vPrintQueueLimit;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
	SET vDone = TRUE;

	SELECT printQueueLimit INTO vPrintQueueLimit
		FROM printQueueConfig;

	SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum
		FROM printQueue WHERE statusCode = 'queued';

	SELECT isAlreadyNotified INTO vIsAlreadyNotified
		FROM printingQueueCheck;

	IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND
		(SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND
		vIsAlreadyNotified = FALSE AND vCurrentCount  > 0
	THEN

		SELECT  '<table  cellspacing="10">\n\t\t\t\t\t<tr>\n\t\t\t\t\t\t<td>Id Cola</td>\n\t\t\t\t\t\t<td>Ruta Impresora</td>\n\t\t\t\t\t\t<td>Informe</td>\n\t\t\t\t\t\t<td>Estado</td>\n\t\t\t\t\t\t<td>Trabajador</td>\n\t\t\t\t\t\t<td>Error</td>\n\t\t\t\t\t</tr>' INTO vTableQueue;

		OPEN vCur;

		l: LOOP

			SET vDone = FALSE;

			FETCH vCur INTO vLineQueue;

			IF vDone THEN
				LEAVE l;
			END IF;

			SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue;

		END LOOP;

		CLOSE vCur;

		CALL mail_insert(
			'cau@verdnatura.es',
			NULL,
			'Servidor de impresion parado',
			CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '</table>')
		);

			UPDATE printingQueueCheck SET isAlreadyNotified = TRUE;
	END IF;

	IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND
		vIsAlreadyNotified = TRUE
	THEN
		UPDATE printingQueueCheck SET isAlreadyNotified = FALSE;
	END IF;

	UPDATE printingQueueCheck
		SET lastCount = vCurrentCount,
			lastCheckSum = vCheckSum;

END$$
DELIMITER ;
