DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setState`(
	vSelf INT,
	vStateCode VARCHAR(255) COLLATE utf8_general_ci
)
BEGIN
/**
 * Modifica el estado de un ticket si se cumplen las condiciones necesarias.
 *
 * @param vSelf el id del ticket
 * @param vStateCode estado a modificar del ticket
 */
	DECLARE vticketAlertLevel INT;
	DECLARE vTicketStateCode VARCHAR(255);
	DECLARE vCanChangeState BOOL;
	DECLARE vPackedAlertLevel INT;
	DECLARE vZoneFk INT;

	SELECT s.alertLevel, s.`code`, t.zoneFk
		INTO vticketAlertLevel, vTicketStateCode,  vZoneFk
		FROM state s
			JOIN ticketTracking tt ON tt.stateFk = s.id
			JOIN ticket t ON t.id = tt.ticketFk
		WHERE tt.ticketFk = vSelf
		ORDER BY tt.created DESC
		LIMIT 1;

	SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; 

	IF vStateCode = 'OK' AND vZoneFk IS NULL THEN
		CALL util.throw('ASSIGN_ZONE_FIRST');
	END IF;

	SET vCanChangeState = (
			vStateCode <> 'ON_CHECKING' OR 
			vticketAlertLevel < vPackedAlertLevel
		)AND NOT (
			vTicketStateCode IN ('CHECKED', 'CHECKING')
			AND vStateCode IN ('PREPARED', 'ON_PREPARATION')
		);

	IF vCanChangeState THEN
		INSERT INTO ticketTracking (stateFk, ticketFk, workerFk)
			SELECT id, vSelf, account.myUser_getId()
				FROM state
				WHERE `code` = vStateCode COLLATE utf8_unicode_ci;
				
		IF vStateCode = 'PACKED' THEN
			CALL ticket_doCmr(vSelf);
		END IF;
	ELSE
		CALL util.throw('INCORRECT_TICKET_STATE');
	END IF;
END$$
DELIMITER ;
