ALTER PROCEDURE [dbo].[stp_GetMachineProdData]
AS
BEGIN
     -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    
    BEGIN tran
    
    	-- dichiarazioni variabili x recupero dati
    	DECLARE @LastIdx	INT = 0
    	DECLARE @NewIdx		INT = 0
    		
    	-- recupero valore ultima riga stato processata...
    	SELECT	@LastIdx = ISNULL(LastIdx,0)
    	FROM	SyncState
    	WHERE	TableName = 'ToMachineProdData'
    
    	-- recupero nuovo MAX idx
    	SELECT	@NewIdx = ISNULL(MAX(ID),0)
    	FROM	syn_M2ERP_PRODORDERS
		
		-- eseguo SOLO SE ho dati aggiuntivi...
		IF(@NewIdx > @LastIdx)
		BEGIN
    		/* --------------------------------------------------
    		* Invierò solo VARIAZIONI dei valori
			* - CurrentProdOrder (iniziato/concluso)
			* - Quantità Produzione
			* - dati FluxLog x ordini/quantità/tempi di produzione
			*
			* andando ad incrociare ogni record col precedente...
    		* -------------------------------------------------- */
    
			-- processo dati ORDINI
			;WITH cteCurrOrd AS
    		(
    			SELECT	ID
						,ProdOrder
						,Targa as IdxMacchina
						,[DateTime] AS DtEvento
						,ProdOrderState
						,ProdQty
    			FROM	syn_M2ERP_PRODORDERS
    			WHERE	ID > @LastIdx AND ID <= @NewIdx
    		)
			, ctePrevOrd AS
    		(
    			SELECT	ID
						,ProdOrder
						,Targa as IdxMacchina
						,[DateTime] AS DtEvento
						,ProdOrderState
						,ProdQty
    			FROM	syn_M2ERP_PRODORDERS
    			WHERE	ID >= @LastIdx AND ID < @NewIdx
    		)
			, cteActDec AS
			(
				SELECT	curr.DtEvento as DtEve 
						,curr.IdxMacchina 
						,CASE 
							WHEN curr.ProdOrderState = 1 THEN 'StartOrd' 
							--WHEN curr.ProdOrderState = 2 THEN 'PauseOrd'
							WHEN curr.ProdOrderState = 3 THEN 'EndOrd'
							--WHEN curr.ProdOrderState = 6 THEN 'InsOrd' 
							ELSE 'NONE'
							END AS OrdAction
						,CASE 
							WHEN LEFT(curr.ProdOrder, 4) = 'PODL' THEN REPLACE(curr.ProdOrder,'PODL','')
							ELSE 0 END AS IdxPodl
						,CASE 
							WHEN LEFT(curr.ProdOrder, 3) = 'ODL' THEN REPLACE(curr.ProdOrder,'ODL','')
							ELSE 0 END AS IdxOdl
						,curr.ProdOrder as CodComm
						,curr.ProdQty as PzCount
				FROM	cteCurrOrd curr
					INNER JOIN ctePrevOrd prev
					ON	curr.ID = prev.ID+1
				WHERE	(curr.ProdOrder <> prev.ProdOrder)
					OR	(curr.ProdOrderState <> prev.ProdOrderState)
					OR	(curr.ProdQty <> prev.ProdQty)
			)
			-- lego i valori col precedente x calcolare se siano variati x insert valori
    		INSERT INTO	MachineProdData(DtEve, IdxMacchina, Action, IdxPodl, IdxOdl, CodComm, PzCount)
			SELECT	DtEve, IdxMacchina, OrdAction, IdxPodl, IdxOdl, CodComm, PzCount
			FROM	cteActDec
			WHERE	OrdAction <> 'NONE'

			-- ora processo ANCHE come fluxLog i record dei degli ordini (cod ordine, tempi...)
			;WITH cteCurrOrd AS
			(
				SELECT	ID
						,ProdOrder
						,Targa as IdxMacchina
						,[DateTime] AS DtEvento
						,ProdOrderState
						,ProdQty
						,ElapsedTime
				FROM	syn_M2ERP_PRODORDERS
				WHERE	ID > @LastIdx AND ID <= @NewIdx
			)
			, ctePrevOrd AS
			(
				SELECT	ID
						,ProdOrder
						,Targa as IdxMacchina
						,[DateTime] AS DtEvento
						,ProdOrderState
						,ProdQty
						,ElapsedTime
				FROM	syn_M2ERP_PRODORDERS
				WHERE	ID >= @LastIdx AND ID < @NewIdx
			)
			, cteActDec AS
			(
				SELECT	curr.DtEvento as DtEve 
						,curr.IdxMacchina 
						,CASE 
							WHEN curr.ProdOrderState = 1 THEN 'StartOrd' 
							--WHEN curr.ProdOrderState = 2 THEN 'PauseOrd'
							WHEN curr.ProdOrderState = 3 THEN 'EndOrd'
							--WHEN curr.ProdOrderState = 6 THEN 'InsOrd' 
							ELSE 'NONE'
							END AS OrdAction
						,CAST(CASE 
							WHEN LEFT(curr.ProdOrder, 4) = 'PODL' THEN REPLACE(curr.ProdOrder,'PODL','')
							ELSE '0' END AS NVARCHAR(50)) AS IdxPodl
						,CAST(CASE 
							WHEN LEFT(curr.ProdOrder, 3) = 'ODL' THEN REPLACE(curr.ProdOrder,'ODL','')
							ELSE '0' END AS NVARCHAR(50)) AS IdxOdl
						,CAST(curr.ProdOrder AS NVARCHAR(50)) as CodComm
						,curr.ProdQty as PzCount
						,CAST(curr.ElapsedTime AS NVARCHAR(50)) AS ElapsedTime
				FROM	cteCurrOrd curr
					INNER JOIN ctePrevOrd prev
					ON	curr.ID = prev.ID+1
				WHERE	(curr.ProdOrder <> prev.ProdOrder)
					OR	(curr.ProdOrderState <> prev.ProdOrderState)
					OR	(curr.ProdQty <> prev.ProdQty)
			)
			-- lego i valori col precedente x calcolare se siano variati x insert valori
			--INSERT INTO	MachineFluxLog(DtEvento, IdxMacchina, CodFlux, Valore, Cnt)
			SELECT	DtEve as DtEvento, IdxMacchina, CodFlux, Valore,0 as Cnt
			FROM	cteActDec
			UNPIVOT (Valore FOR CodFlux IN (CodComm, ElapsedTime, IdxOdl, IdxPOdl)) AS Unpvt
			WHERE	OrdAction <> 'NONE'
				AND	Valore <> '0'

    		-- aggiorno valore indice processato
    		MERGE SyncState AS tgt  
    		USING (SELECT @NewIdx as LastIdx, 'ToMachineProdData' AS TableName) as src (LastIdx, TableName)  
    		ON (tgt.TableName = src.TableName)  
    		WHEN MATCHED THEN
    			UPDATE SET	LastIdx = src.LastIdx  
    						,Note	= 'UPDATED from ' + CAST(@LastIdx AS NVARCHAR(50))
    						,LastUpdate = GETDATE()
    		WHEN NOT MATCHED THEN  
    			INSERT (LastIdx, TableName, Note, LastUpdate)  
    			VALUES (src.LastIdx, src.TableName, 'CREATED', GETDATE());

		END
    		
    COMMIT tran
    
END
