USE `hedera`;
DROP procedure IF EXISTS `orderAddItem`;

DELIMITER $$
USE `hedera`$$
CREATE DEFINER=`root`@`%` PROCEDURE `orderAddItem`(
	vOrder INT,
    vWarehouse INT,
    vItem INT,
    vAmount INT)
BEGIN
	DECLARE vRow INT;
    DECLARE vAdd INT;
	DECLARE vAvailable INT;
	DECLARE vDone BOOL;
	DECLARE vGrouping INT;
    DECLARE vRate INT;
    DECLARE vShipment DATE;
	DECLARE vPrice DECIMAL(10,2);
	DECLARE vDate DATE;
    DECLARE vAddress INT;
    DECLARE vAgencyMode INT;
	DECLARE cur CURSOR FOR
		SELECT grouping, price, rate
			FROM tmp.bionic_price
			WHERE warehouse_id = vWarehouse
				AND item_id = vItem
			ORDER BY grouping DESC;
            
	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;
        
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

    SELECT date_send, address_id, agency_id
		INTO vDate, vAddress, vAgencyMode
		FROM `order`
        WHERE id = vOrder;

	CALL vn2008.bionic_from_item(vDate, vAddress, vAgencyMode, vItem);

	START TRANSACTION;

    SELECT shipped INTO vShipment
		FROM tmp.travel_tree
        WHERE warehouseFk = vWarehouse;
    
	SELECT available INTO vAvailable
		FROM tmp.bionic_lot
		WHERE warehouse_id = vWarehouse
			AND item_id = vItem;
			
	IF vAmount > vAvailable
	THEN
		CALL util.throw ('ORDER_ROW_UNAVAILABLE');
	END IF;
	
    OPEN cur;
    
	l: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vGrouping, vPrice, vRate;

		IF vDone THEN
			LEAVE l;
		END IF;
        
        SET vAdd = vAmount - MOD(vAmount, vGrouping);
        SET vAmount = vAmount - vAdd;

		IF vAdd = 0 THEN
			ITERATE l;
		END IF;

		INSERT INTO order_row SET
			order_id = vOrder,
            item_id = vItem,
            warehouse_id = vWarehouse,
            shipment = vShipment,
            rate = vRate,
            amount = vAdd,
            price = vPrice;
			
		SET vRow = LAST_INSERT_ID();

		INSERT INTO order_component (order_row_id, component_id, price)
			SELECT vRow, c.component_id, c.cost
				FROM tmp.bionic_component c
					JOIN bi.tarifa_componentes t
						ON t.Id_Componente = c.component_id
						AND (t.tarifa_class IS NULL OR t.tarifa_class = vRate)
				WHERE c.warehouse_id = vWarehouse
					AND c.item_id = vItem;
	END LOOP;
    
    CLOSE cur;				
	COMMIT;
    
    CALL vn2008.bionic_free ();
END$$

DELIMITER ;

