-- dbo.ep_HDCDZApi_ZpracujPrijataData
CREATE PROCEDURE dbo.ep_HDCDZApi_ZpracujPrijataData
      @idJson INT=NULL
AS

SET NOCOUNT ON
-- ! proceduru neupravujte, bude stejne pregenerovana pri startu Windows sluzby HDCDZApi !




IF OBJECT_ID(N'dbo.Tabx_HDC_API_DigitalizaceSoubory', N'U') IS NULL
 BEGIN
  IF OBJECT_ID(N'dbo._hdc_ph_Log', N'U') IS NOT NULL
   INSERT dbo._hdc_ph_Log (LogText) SELECT N'Neexistuje tabulka Tabx_HDC_API_DigitalizaceSoubory'
  RETURN
 END




DECLARE
 @errMsg NVARCHAR(500)=N'',
 @errProc NVARCHAR(100),
 @tranPred INT,
 @iChyba INT,
 @bChyba BIT,
 @iTemp INT,
 @debugXML XML,
 @idUziv INT

DECLARE
 @jsonString NVARCHAR(max),
 @docsJson NVARCHAR(max),
 @soubor NVARCHAR(100),
 @dataZoneId INT,
 @docNum INT,
 @ordNum NVARCHAR(15), -- zakazka,
 @docUrl NVARCHAR(255),
 @jeNacteno BIT,
 @jeKpl BIT,
 @pgTotal INT,
 @pgRead INT,
 @cisZam INT

DROP TABLE IF EXISTS #TabJSONData
CREATE TABLE #TabJSONData (ID INT IDENTITY(1,1) NOT NULL, doc NVARCHAR(max) )






IF (@idJson IS NOT NULL)
  DECLARE j CURSOR LOCAL FOR
   SELECT ID, JsonData FROM dbo._hdc_ph_PrijataJsonData WHERE ID=@idJson
 ELSE
  DECLARE j CURSOR LOCAL FOR
   SELECT ID, JsonData
    FROM dbo._hdc_ph_PrijataJsonData
    WHERE Blokovano=0
      AND DatZpracovani IS NULL
      AND ISNULL(JSONData,N'')<>N''
    ORDER BY DatPorizeni
OPEN j
WHILE (1=1)
 BEGIN
  FETCH NEXT FROM j INTO @idJson, @jsonString
  IF (@@FETCH_STATUS<>0) BREAK

  IF (ISJSON(@jsonString)=0)
   BEGIN
    UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), PosledniChyba=N'Neplatna JSON data' WHERE ID=@idJson
   END


  BEGIN TRY
   SET @tranPred=@@TRANCOUNT
   IF (@tranPred=0)
    BEGIN TRAN

-- smaz pomocnou tabulku
   DELETE FROM #TabJSONData
   INSERT #TabJSONData (doc) SELECT @jsonString

   UPDATE dbo._hdc_ph_PrijataJsonData SET PosledniChyba=NULL, CisloZam=@cisZam, Blokovano=1 WHERE ID=@idJson


   SELECT @dataZoneId=JSON_VALUE(d.doc, '$.datazoneId'),
          @soubor=JSON_VALUE(d.doc, '$.file'),
          @docsJson = d2.documents
    FROM #TabJSONData d
         CROSS APPLY OPENJSON(d.doc, N'$')
          WITH ([documents] NVARCHAR(max) AS JSON) AS d2

   SET @soubor=ISNULL(@soubor, N'')
   IF (@soubor<>N'')
    UPDATE dbo._hdc_ph_PrijataJsonData SET UzivIdent=@soubor WHERE ID=@idJson

   IF (@docsJson<>N'')
    BEGIN
     IF (ISJSON(@docsJson)=1)
      BEGIN
       DELETE FROM #TabJSONData
       INSERT #TabJSONData (doc) SELECT @docsJson

       DECLARE docs CURSOR LOCAL FOR
        SELECT detail.idDoklad, detail.cisloZakazky, ISNULL(detail.jeNacteno,0), ISNULL(detail.jeKpl,0),
               ISNULL(detail.pgCount,0), ISNULL(detail.pgRead,0), detail.docUrl
         FROM #TabJSONData d
          CROSS APPLY OPENJSON (d.doc, N'$')
           WITH (idDoklad INT '$.documentNumber',
                 cisloZakazky NVARCHAR(15) '$.orderNumber',
                 jeNacteno BIT '$.isNotFound',
                 jeKpl BIT '$.isComplete',
                 pgCount INT '$.pageCountTotal',
                 pgRead INT '$.pageCountRead',
                 docURL NVARCHAR(255) '$.documentUrl') AS detail
       OPEN docs
       WHILE (1=1)
        BEGIN           
         FETCH NEXT FROM docs INTO @docNum, @ordNum, @jeNacteno, @jeKpl, @pgTotal, @pgRead, @docUrl
         IF (@@FETCH_STATUS<>0) BREAK

         IF (CHARINDEX(N'NotFound', @docUrl)=0)
           BEGIN
            IF NOT EXISTS (SELECT 1 FROM dbo.Tabx_HDC_API_DigitalizaceSoubory WHERE DocNumber=@docNum AND OrderNumber=@ordNum AND DocURL=@docUrl)
             INSERT dbo.Tabx_HDC_API_DigitalizaceSoubory (IDJsonData, IDDZDoc, DocNumber, OrderNumber, IsComplete, IsNotFound, PagesTotal, PagesRead, DocURL, IDDokladOZ)
              SELECT @idJson, @dataZoneId, @docNum, @ordNum, @jeKpl, @jeNacteno, @pgTotal, @pgRead, @docUrl, @docNum
           END
          ELSE
           BEGIN
            IF NOT EXISTS (SELECT 1 FROM dbo.Tabx_HDC_API_DigitalizaceSoubory WHERE DocURL=@docUrl)
             INSERT dbo.Tabx_HDC_API_DigitalizaceSoubory (IDJsonData, IDDZDoc, IsComplete, IsNotFound, PagesTotal, PagesRead, DocURL, IDDokladOZ)
              SELECT @idJson, @dataZoneId, @jeKpl, @jeNacteno, @pgTotal, @pgRead, @docUrl, @docNum
           END
        END
       CLOSE docs
       DEALLOCATE docs

      END -- ISJSON(@jsonString)=1
    END -- @docsJson<>''


   UPDATE dbo._hdc_ph_PrijataJsonData SET Blokovano=0, DatZpracovani=GETDATE() WHERE ID=@idJson
   IF (@tranPred=0) AND (@@TRANCOUNT>0)
    COMMIT TRAN
  END TRY
  BEGIN CATCH
   SET @errMsg = ERROR_MESSAGE()
   SET @errProc = ERROR_PROCEDURE()
   IF (@tranPred=0) AND (@@TRANCOUNT>0)
    ROLLBACK TRAN
   UPDATE dbo._hdc_ph_PrijataJsonData SET DatZpracovani=GETDATE(), PosledniChyba=N'CHYBA: ' + @errMsg WHERE ID=@idJson
  END CATCH

 END
CLOSE j
DEALLOCATE j



-- cisteni
DROP TABLE IF EXISTS #TabJSONData
