DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `srt`.`expedition_setDimensions`(
	vExpeditionFk INT,
	vWeight DECIMAL(10,2),
	vLength INT,
	vWidth INT,
	vHeight INT,
	OUT vExpeditionOutFk INT)
BEGIN
/**
 * Actualiza las dimensiones, peso y estado de una expedición
 *
 * @param vExpeditionFk Identificador de expedition
 * @param vWeight Peso en kilos
 * @param vLength Byte con el número de fotocélulas activadas a lo largo
 * @param vWidth Byte con el número de fotocélulas activadas a lo ancho
 * @param vHeight Altura de la caja en cm
 * @return vExpeditionOutFk Identificador de expedition
 */
	
	DECLARE vWidthSensorsUsed INT;
	DECLARE vLengthSensorsUsed INT;

	SET vExpeditionOutFk = expedition_check(vExpeditionFk);

	#primer bit a 1 a la izquierda - primer bit a 1 a la derecha
	SET vWidthSensorsUsed = length(BIN(vWidth)) - LOG2(vWidth & -vWidth);
	SET vLengthSensorsUsed = length(BIN(vLength)) - LOG2(vLength & -vLength);

	UPDATE expedition e
			JOIN expeditionState es ON es.`description` = 'WEIGHED'
			JOIN config c
		SET weight = IFNULL(vWeight, 0),
			stateFk = es.id,
			width = IFNULL(c.widthToFirstSensor + (c.widthSensorSpacing * vWidthSensorsUsed), 0), 
			`length` = IFNULL(c.lengthToFirstSensor + (c.lengthSensorSpacing * vLengthSensorsUsed), 0), 
			height = IFNULL(vHeight * 10, 0)
		WHERE e.id = vExpeditionOutFk;

	SET vExpeditionOutFk = vExpeditionFk;

END$$
DELIMITER ;
