DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`entry_beforeUpdate`
	BEFORE UPDATE ON `entry`
	FOR EACH ROW
BEGIN
	DECLARE vIsVirtual BOOL;
	DECLARE vPrintedCount INT;
	DECLARE vHasDistinctWarehouses BOOL;
	DECLARE vEntryFkCount INT;
	
	IF NEW.isBooked = OLD.isBooked THEN
		CALL entry_checkBooked(OLD.id);
	END IF;

	IF NEW.isBooked = 1 THEN
		SELECT COUNT(*) INTO vEntryFkCount
			FROM buy WHERE entryFk = NEW.id;
		IF vEntryFkCount = 0 THEN
			CALL util.throw('The entry cannot be marked as booked if it does not have lines');
		END IF;
	END IF;

	SET NEW.editorFk = account.myUser_getId();

	IF NOT (NEW.travelFk <=> OLD.travelFk) THEN

		IF NEW.travelFk IS NOT NULL AND NOT travel_hasUniqueAwb(NEW.travelFk) THEN
			CALL util.throw('The travel is incorrect, there is a different AWB in the associated entries');	
		END IF;
	
		SELECT COUNT(*) > 0 INTO vIsVirtual
			FROM entryVirtual WHERE entryFk = NEW.id;

		SELECT NOT (o.warehouseInFk <=> n.warehouseInFk)
			OR NOT (o.warehouseOutFk <=> n.warehouseOutFk)
			INTO vHasDistinctWarehouses
			FROM travel o, travel n
			WHERE o.id = OLD.travelFk
				AND n.id = NEW.travelFk;

		IF vIsVirtual AND vHasDistinctWarehouses THEN
			SIGNAL SQLSTATE '45000'
				SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses';
		END IF;

		IF NEW.travelFk IS NULL THEN
			SELECT COUNT(*) INTO vPrintedCount
				FROM buy
				WHERE entryFk = OLD.id
					AND printedStickers > 0;

			IF vPrintedCount > 0 THEN
				SIGNAL SQLSTATE '45000'
					SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted';
			END IF;
		END IF;
	END IF;

	IF NOT (NEW.supplierFk <=> OLD.supplierFk) THEN
		CALL supplier_checkIsActive(NEW.supplierFk);
		SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk);
	END IF;

	IF NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN 
		SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk, NEW.supplierFk);
	END IF;
END$$
DELIMITER ;
