DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_assign`(vUserFk INT, OUT vCollectionFk INT)
proc:BEGIN   
/* Comprueba si existen colecciones libres que se ajustan al perfil del usuario
 * y le asigna la más antigua.
 * Añade un registro al semillero de colecciones
 */
	DECLARE vHasTooMuchCollections BOOL;
	DECLARE vLockTime INT DEFAULT 15;

	-- Si hay colecciones sin terminar,  sale del proceso
	CALL vn.collection_get(vUserFk);

	SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0
		INTO vHasTooMuchCollections
		FROM tCollection
			JOIN vn.productionConfig pc ;

	DROP TEMPORARY TABLE tCollection;

	IF vHasTooMuchCollections THEN
		CALL util.throw('Hay colecciones pendientes');
		LEAVE proc;
	END IF;

	IF NOT GET_LOCK('collection_assign',vLockTime) THEN
		LEAVE proc;
	END IF;

	-- Se eliminan las colecciones sin asignar que estan obsoletas
	INSERT INTO ticketTracking(stateFk, ticketFk)
			SELECT s.id, tc.ticketFk
				FROM vn.collection c
					JOIN vn.ticketCollection tc ON tc.collectionFk = c.id
					JOIN vn.state s ON s.code = 'PRINTED_AUTO'
					JOIN vn.productionConfig pc 
			WHERE c.workerFk IS NULL 
				AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;

	DELETE c.*
		FROM vn.collection c
			JOIN vn.productionConfig pc 
		WHERE c.workerFk IS NULL 
			AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime;

	-- Se a�ade registro al semillero
	INSERT INTO vn.collectionHotbed(userFk)
		VALUES(vUserFk);

	-- Comprueba si hay colecciones disponibles que se ajustan a su configuracion
	SELECT MIN(c.id)
		INTO vCollectionFk
		FROM vn.collection c 
			JOIN vn.operator o 
				ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL)
				AND o.numberOfWagons = c.wagons
				AND o.trainFk = c.trainFk
				AND o.warehouseFk = c.warehouseFk
				AND c.workerFk IS NULL
		WHERE o.workerFk = vUserFk;

	IF vCollectionFk IS NULL THEN
		CALL vn.collection_new(vUserFk, vCollectionFk);
	END IF;

	UPDATE vn.collection
			SET workerFk = vUserFk
			WHERE id = vCollectionFk;

	DO RELEASE_LOCK('collection_assign');
END$$
DELIMITER ;
