Imports System.ServiceModel.Configuration
Imports com
Imports Therefore.API
Public Class cTherefore

    Shared Function saveFileTo_ImportFolder(Path As String, FilialeAbfertigungsNr As String, AvisoId As String, FirmaId As String, Optional deleteFileAfterImport As Boolean = False)
        FilialeAbfertigungsNr = FilialeAbfertigungsNr.Replace(";", " ")
        FilialeAbfertigungsNr = FilialeAbfertigungsNr.Replace("/", " ")
        FilialeAbfertigungsNr = FilialeAbfertigungsNr.Replace("-", " ")
        If FilialeAbfertigungsNr.Length > 30 Then FilialeAbfertigungsNr = FilialeAbfertigungsNr.ToString.Substring(0, 30)
        Select Case FirmaId
            Case 7
                Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Atilla ab Juni 2011",, deleteFileAfterImport)
            Case 21, 22, 23
                'Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2021 UNISPED", "UNISPED\Import ab Jänner 2021 UNISPED DE", deleteFileAfterImport)
                'Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2021 UNISPED", "Import ab Jänner 2021 UNISPED DE", deleteFileAfterImport)

                Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2021 UNISPED_DE", "UNISPED Zollakten", deleteFileAfterImport)
                  'Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, 394, 394, deleteFileAfterImport)
            Case 1, 11, 20, 17 ', 15 
                '   Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import an Jänner 2019", "Import ab Jänner 2019", deleteFileAfterImport)
                'Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2021", "Import ab Jänner 2021", deleteFileAfterImport)
                'Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2022", "Import ab Jänner 2022", deleteFileAfterImport)
                'Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2023", "Import ab Jänner 2023", deleteFileAfterImport)
                Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2024", "Import ab Jänner 2024", deleteFileAfterImport)
                '  Return saveFileTo_ImportFolderCat(Path, FilialeAbfertigungsNr, AvisoId, "Import ab Jänner 2020", "Import ab Jänner 2020", deleteFileAfterImport)
            Case Else
                Return False
        End Select
    End Function

    Shared Function getFileFromFolderCat(Path As String, FilialeAbfertigungsNr As String, AvisoId As String, Category As String, Optional Category2 As String = "", Optional deleteFileAfterImport As Boolean = False)
        Try
            '  MsgBox("go: ")

            'Dim SQL_VERAG As New VERAG_PROG_ALLGEMEIN.SQL

            'Dim abfertNr = FilialeAbfertigungsNr
            'Dim docid As String = ""
            'Dim Filiale = FilialeAbfertigungsNr.Substring(0, 4)

            'If Filiale = 4801 Then
            '    docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat17] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            'ElseIf Filiale = 5601 Then
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat393] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat394] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            'ElseIf Filiale = 5701 Then
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat395] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat397] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            'Else
            '    docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].TheCat1083 WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat889] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat398] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat291] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat153] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat119] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat109] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat101] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat84] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat72] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat59] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat36] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat14] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON")
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat130] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON") ' WAI
            '    If Not IsNumeric(docid) OrElse docid <= 0 Then docid = SQL_VERAG.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM [Therefore].[dbo].[TheCat131] WHERE [String] LIKE '" & abfertNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON") ' SBG
            'End If

            'If IsNumeric(docid) AndAlso docid > 0 Then
            '    '  Process.Start("theviewer.exe -" & docid)
            '    '    Process.Start("C:\Program Files (x86)\Therefore\theviewer.exe -" & docid)
            '    Try
            '        Shell("C:\Program Files (x86)\Therefore\theviewer.exe -d" & docid)
            '    Catch ex As Exception
            '        Shell("C:\Program Files\Therefore\theviewer.exe -d" & docid)
            '    End Try
            'Else
            '    MsgBox("Das Dokument konnte nicht gefunden werden.")
            'End If


            If Category2 = "" Then Category2 = Category
            Dim SQL As New SQL

            ' 1. Connect to the Therefore™ Server
            Dim server As New TheServer
            server.Connect(TheClientType.CustomApplication)

            ' 2. Create a new Therefore™ Document
            Dim doc As New TheDocument()



            ' 3. Retrieve the document from the server to the inbox

            Dim inbox As String = Path

            Dim TableName = ""
            If IsNumeric(Category) Then
                TableName = "TheCat" & Category
                If SQL.getValueTxtBySql("SELECT count(*)  FROM [TheCategory] WHERE TableName='" & TableName & "'", "SCANCANON",,, "") = 0 Then
                    MsgBox("Therefore: Tabelle nicht gefunden: " & TableName)
                    Return False
                End If
            Else
                TableName = SQL.getValueTxtBySql("SELECT TOP 1 [TableName]   FROM [TheCategory] WHERE Title='" & Category & "'", "SCANCANON",,, "")
            End If

            Dim docNo As Integer = SQL.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM  " & TableName & " WHERE [String] LIKE '" & FilialeAbfertigungsNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON",,, -1)
            ' MsgBox("docNo: " & docNo)

            Dim extractDir As String = Path & FilialeAbfertigungsNr & "\"
            If Not System.IO.Directory.Exists(extractDir) Then
                System.IO.Directory.CreateDirectory(extractDir)
            End If

            Dim filename As String = ""
            If docNo > 0 Then
                Dim folder = ""
                Dim VerionNo As Integer
                filename = doc.Retrieve(docNo, VerionNo, folder, server, False)
                ' 4. Extract all file streams to the specified directory


                Dim i As Integer



                For i = 0 To doc.StreamCount - 1 Step i + 1

                    Dim extractFile As String = doc.ExtractStream(i, extractDir)

                    Console.WriteLine("File stream extracted to " + extractFile)

                Next

            Else
                'Nicht gefunden, hier hinschreiben:
                Dim file As System.IO.StreamWriter
                file = My.Computer.FileSystem.OpenTextFileWriter(Path & "notfound.txt", True)
                file.WriteLine(FilialeAbfertigungsNr)
                file.Close()

                ' MsgBox(FilialeAbfertigungsNr)
            End If


            ' 8. Close Therefore™ document object
            doc.Close()

            Return True
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    Shared Function getFileFromFolderCat(Category As String, Optional Category2 As String = "", Optional UpdateExistingVertraege As Boolean = False)
        Try


            If Category2 = "" Then Category2 = Category
            Dim SQL As New SQL

            ' 1. Connect to the Therefore™ Server
            Dim server As New TheServer
            server.Connect(TheClientType.CustomApplication)

            ' 2. Create a new Therefore™ Document


            Dim TableName = ""
            If IsNumeric(Category) Then
                TableName = "TheCat" & Category
                If SQL.getValueTxtBySql("SELECT count(*)  FROM [TheCategory] WHERE TableName='" & TableName & "'", "SCANCANON",,, "") = 0 Then
                    MsgBox("Therefore: Tabelle nicht gefunden: " & TableName)
                    Return False
                End If
            Else
                TableName = SQL.getValueTxtBySql("SELECT [TableName] FROM [TheCategory] WHERE Title='" & Category & "'", "SCANCANON",,, "")
            End If

            Dim docs As DataTable = SQL.loadDgvBySql("SELECT isnull([DocNo],-1) as DocNo,[String],[Eingabedatum] FROM  " & TableName & " where isNUmeric(left(string,6)) = 1", "SCANCANON")

            If Not vbYes = MsgBox("Möchten Sie die " & docs.Rows.Count & " Dokumente aus Therefore als Unternehmensbescheinigung hochladen?" & vbNewLine & "Existierende Datenarchiv-Einträge werden " & IIf(UpdateExistingVertraege, "-ÜBERSCHRIEBEN-", "-ÜBERSPRUNGEN-") & "!", vbYesNoCancel) Then Return False

            For Each TFdoc As DataRow In docs.Rows

                Dim filename As String = ""
                If TFdoc.Item("DocNo") > 0 Then
                    If Not IsDBNull(TFdoc("String")) AndAlso TFdoc("String").ToString() <> "" AndAlso TFdoc.Item("String").ToString.Length > 6 AndAlso IsNumeric(TFdoc.Item("String").ToString.Substring(0, 6)) Then
                        Dim kdNr = TFdoc.Item("String").ToString.Substring(0, 6)

                        Dim Kunde As New cKunde(kdNr)

                        If Kunde IsNot Nothing Then

                            Dim EingabeDatum As Date

                            If Not IsDBNull(TFdoc("Eingabedatum")) AndAlso TFdoc("Eingabedatum").ToString() <> "" AndAlso IsDate(TFdoc.Item("Eingabedatum").ToString) Then

                                EingabeDatum = CDate(TFdoc("Eingabedatum"))
                            Else
                                EingabeDatum = Now()
                            End If


                            Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(Kunde.KundenNr, EingabeDatum, 7)

                            If KV.hasEntry AndAlso KV.kv_datenarchivId IsNot Nothing AndAlso KV.kv_datenarchivId > 0 AndAlso Not UpdateExistingVertraege Then Continue For 'dann nicht aktualisieren!

                            Dim extractDir As String = System.IO.Path.GetTempPath() & Kunde.KundenNr & "\"
                            If Not System.IO.Directory.Exists(extractDir) Then
                                System.IO.Directory.CreateDirectory(extractDir)
                            End If

                            Dim doc As New TheDocument()

                            Dim folder = ""
                            Dim VerionNo As Integer
                            filename = doc.Retrieve(TFdoc.Item("DocNo"), VerionNo, folder, server, False)
                            ' 4. Extract all file streams to the specified directory

                            Dim i As Integer
                            Dim DSID As Integer = -1

                            Dim multiFiles As Boolean = (doc.StreamCount > 1)
                            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "UM-BESCHEINIGUNG", Now.ToString("ddMMyy_HHmmss.ffff"), "", "", "UM-Bescheinigung", Kunde.KundenNr, multiFiles)
                            For i = 0 To doc.StreamCount - 1 'Step i + 1

                                Dim extractFile As String = doc.ExtractStream(i, extractDir)
                                If Not DS.uploadDataToDATENSERVER(extractFile) Then
                                    MsgBox("Fehler beim Hochladen!")
                                End If

                            Next

                            KV.kv_Info = "aus TF importiert"
                            KV.kv_datenarchivId = DS.da_id
                            KV.SAVE()

                            doc.Close()

                        End If
                    End If
                End If


            Next




            Return True
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function


    Shared Function saveFileTo_ImportFolderCat(Path As String, FilialeAbfertigungsNr As String, AvisoId As String, Category As String, Optional Category2 As String = "", Optional deleteFileAfterImport As Boolean = False)
        Try
            If Category2 = "" Then Category2 = Category
            Dim SQL As New SQL

            ' 1. Connect to the Therefore™ Server
            Dim server As New TheServer
            server.Connect(TheClientType.CustomApplication)

            ' 2. Create a new Therefore™ Document
            Dim doc As New TheDocument()

            ' 3. Create temporary File
            'Dim filename As String = ""
            'doc.Create(filename)

            ' 4A. Set Therefore™ Category by Number
            '  doc.IndexData.SetCategory(5, server) 
            ' or 4B. Set Therefore™ Category by Name
            doc.IndexData.SetCategory(Category2, server)

            ' 5. Add streams
            'doc.AddStream("D:\\TestAll\\TestDocs\\Scsi.doc", "", 0)
            'doc.AddStream("D:\\TestAll\\TestDocs\\TEST.xls", "", 0)
            ' 6. Set index data
            'Dim indexData As TheIndexData = doc.IndexData
            'indexData("String") = FilialeAbfertigungsNr
            'indexData("Eingabedatum") = Now.ToShortDateString
            'indexData("LKW_ID") = AvisoId

            'MsgBox(doc.IndexData.Count)
            ' 7. Archive the document 
            'Dim docNo As Integer = doc.Archive(server, 0)
            'Dim docNo As Integer = 0
            'Dim filenameNEW As String = doc.Retrieve(docNo, "", server)
            Dim TableName = ""
            If IsNumeric(Category) Then
                TableName = "TheCat" & Category
                If SQL.getValueTxtBySql("SELECT count(*)  FROM [TheCategory] WHERE TableName='" & TableName & "'", "SCANCANON",,, "") = 0 Then
                    MsgBox("Therefore: Tabelle nicht gefunden: " & TableName)
                    Return False
                End If
            Else
                TableName = SQL.getValueTxtBySql("SELECT TOP 1 [TableName]   FROM [TheCategory] WHERE Title='" & Category & "'", "SCANCANON",,, "")
            End If

            Dim docNo As Integer = SQL.getValueTxtBySql("SELECT TOP 1 isnull([DocNo],-1)  FROM  " & TableName & " WHERE [String] LIKE '" & FilialeAbfertigungsNr & "' ORDER BY [Eingabedatum] DESC", "SCANCANON",,, -1)
            '  MsgBox("docNo: " & docNo)
            Dim filename As String = ""
            If docNo <= 0 Then
                doc.Create(filename)

                doc.AddStream(Path, "", 0)
                Dim indexData As TheIndexData = doc.IndexData
                indexData("String") = FilialeAbfertigungsNr
                indexData("Eingabedatum") = Now.ToShortDateString
                indexData("LKW_ID") = AvisoId

                docNo = doc.Archive(server, 0)
            Else
                Dim folder = ""
                Dim VerionNo As Integer
                filename = doc.Retrieve(docNo, VerionNo, folder, server, False)

                Dim user As String = ""
                doc.CheckOut(server, False, user, VerionNo)

                doc.AddStream(Path, "", 0)
                doc.CheckIn(server)
            End If



            ' 8. Close Therefore™ document object
            doc.Close()

            ' 9. Delete the temporary file
            If deleteFileAfterImport Then System.IO.File.Delete(filename)

            ' 10. Optional: Print a success message on the console
            '   Console.WriteLine("Document successfully archived as " + docNo.ToString() + ".")
            Return True
        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function

    'Shared Function saveFileTo_ImportFolder2(Path As String, FilialeAbfertigungsNr As Integer, AvisoId As Integer)
    '    Try

    '        ' 1. Connect to the Therefore™ Server
    '        Dim server As New TheServer
    '        server.Connect(TheClientType.CustomApplication)

    '        ' 2. Create a new Therefore™ Document
    '        Dim doc As New TheDocument()

    '        ' 3. Create temporary File
    '        Dim filename As String = ""
    '        doc.Create(filename)

    '        ' 4A. Set Therefore™ Category by Number
    '        '  doc.IndexData.SetCategory(5, server) 
    '        ' or 4B. Set Therefore™ Category by Name
    '        doc.IndexData.SetCategory("Import ab Jänner 2019", server)

    '        ' 5. Add streams
    '        'doc.AddStream("D:\\TestAll\\TestDocs\\Scsi.doc", "", 0)
    '        'doc.AddStream("D:\\TestAll\\TestDocs\\TEST.xls", "", 0)
    '        doc.AddStream(Path, "", 0)
    '        ' 6. Set index data

    '        '    MsgBox(doc.IndexData.Count)
    '        ' 7. Archive the document 
    '        Dim docNo As Integer = doc.Archive(server, 0)
    '        MsgBox(docNo)

    '        ' 8. Close Therefore™ document object
    '        doc.Close()

    '        ' 9. Delete the temporary file
    '        System.IO.File.Delete(filename)

    '        ' 10. Optional: Print a success message on the console
    '        '   Console.WriteLine("Document successfully archived as " + docNo.ToString() + ".")

    '    Catch ex As Exception
    '        MsgBox(ex.Message & ex.StackTrace)
    '    End Try
    'End Function
End Class
