Imports System.Data.SqlClient
Imports System.IO

Module AtlasAufschubDatenEinlesen

    Public Sub initAllFiles(path As String, HISTORY As Boolean) 'Alle Files im Ordner durchlaufen 
        For Each file As String In System.IO.Directory.GetFiles(path)
            If HISTORY Then
                initFile(file)
            Else
                Dim FI As New System.IO.FileInfo(file)
                Dim LastWriteDate As Date = FI.LastWriteTime
                If LastWriteDate > Now.AddDays(-6) Then
                    initFile(file)
                End If
            End If
        Next
        insertSQL()
    End Sub
    Sub writeLineToSqlInsert(brgak_datum, brgak_betrag, brgak_brgaktoId, brgak_filename, brgak_atc, brgak_fileline)
        Try
            Using sr As New StreamWriter(AppDomain.CurrentDomain.BaseDirectory & "sql.txt", True)
                sr.WriteLine(brgak_datum & ";" & brgak_betrag & ";" & brgak_brgaktoId & ";" & brgak_filename & ";" & brgak_atc & ";" & brgak_fileline)
            End Using
        Catch ex As Exception
            writeLog("ERROR", "Fehler beim Schreiben der SQL Datei: " & ex.Message)
        End Try
    End Sub
    Public Sub insertSQL()
        If System.IO.File.Exists(AppDomain.CurrentDomain.BaseDirectory & "sql.txt") Then
            Try
                Using sr As New StreamReader(AppDomain.CurrentDomain.BaseDirectory & "sql.txt")
                    Dim line As String = ""
                    Do While sr.Peek() >= 0
                        line = sr.ReadLine
                        If line.Contains(";") Then
                            Dim split = line.Split(";")
                            If tryToInsertProgramm(split(0), CDbl(split(1)), split(2), split(3), split(4), split(5)) Then
                                'Try
                                'Catch ex As Exception
                                ' End Try
                            End If
                        End If
                    Loop
                End Using
                My.Computer.FileSystem.WriteAllText(AppDomain.CurrentDomain.BaseDirectory & "sql.txt", "", False)
            Catch ex As Exception
                writeLog("ERROR", "Fehler beim Lesen der SQL Datei: " & ex.Message)
            End Try
        End If
    End Sub


    Dim POS_head = 0
    Dim POS_AbgKto = 6
    Dim POS_AbgBetr = 11
    Dim POS_ATC = 1

    Public Sub initFile(file As String)
        Dim checkfile As Boolean = False
        Try
            Using sr As New StreamReader(file)
                If Not file.ToLower.EndsWith("tmp") Then
                    Dim t As DateTime = Now

                    Do
                        checkfile = FileInUse(file)
                    Loop Until checkfile = True Or t.AddSeconds(3) < Now

                    Dim line As String = ""
                    Dim rowcnt = 1
                    Do While sr.Peek() >= 0
                        line = CStr(sr.ReadLine())
                        Dim s = line.Split(Chr(29)) 'nach GroupSeperator splitten   
                        If s(POS_head) = "ASK" AndAlso s(POS_AbgKto) = "006128" Then
                            Dim filename = cut_file(file)
                            Dim betrag As Double = CDbl(s(POS_AbgBetr).Substring(0, 9) & "," & s(POS_AbgBetr).Substring(9, 2))
                            '    MsgBox(betrag)
                            Dim fi As New System.IO.FileInfo(file)
                            writeLineToSqlInsert(fi.CreationTime.ToString("dd.MM.yyyy hh:mm:ss"), betrag, "1", filename, s(POS_ATC), rowcnt)
                            'If rowcnt > 1 Then MsgBox(filename)
                        End If
                        rowcnt += 1
                    Loop
                    '  writeLogVerarbeitet(cut_file(file))
                End If
            End Using
        Catch ex As Exception
            writeLog("ERROR", "Fehler beim Initialisieren der ATLAS-Datei: " & ex.Message)
        End Try
        insertSQL()
    End Sub

    Private Function cut_file(ByVal file As String) As String ' Funktion zum Entfernen der Backslashs / Ordner While file.Contains("\") file = file.Remove(0, 1) End While Return file End Function 
        While file.Contains("\")
            file = file.Remove(0, 1)
        End While
        Return file
    End Function

   Public Function FileInUse(ByVal sFile As String) As Boolean
        If System.IO.File.Exists(sFile) Then
            Try
                Dim F As Short = FreeFile()
                FileOpen(F, sFile, System.IO.FileMode.Open, OpenAccess.Read, OpenShare.LockRead)
                FileClose(F)
            Catch
                Return True
            End Try
        End If
        Return False
    End Function

    Public Function tryToInsertProgramm(brgak_datum, brgak_betrag, brgak_brgaktoId, brgak_filename, brgak_atc, brgak_fileline) As Boolean

        Dim sql As String = " begin tran" &
                            " if Not exists (select * from tblBrgAufschub with (updlock,serializable) where brgak_filename = @brgak_filename AND  brgak_fileline=@brgak_fileline) " &
                                   " begin " &
                                   " INSERT INTO tblBrgAufschub " &
                                   " (brgak_datum, brgak_betrag, brgak_brgaktoId, brgak_filename, brgak_atc,brgak_fileline) VALUES " &
                                   " (@brgak_datum, @brgak_betrag, @brgak_brgaktoId, @brgak_filename, @brgak_atc,@brgak_fileline) " &
                                " End " &
                                " commit tran "
        '(brgak_fileline='' OR ... )

        ' " ELSE " &
        '    " begin " &
        '       " UPDATE tblBrgAufschub " &
        '      " SET brgak_datum=@brgak_datum, brgak_betrag=@brgak_betrag, brgak_brgaktoId=@brgak_brgaktoId, brgak_filename=@brgak_filename, brgak_atc=@brgak_atc,brgak_fileline=@brgak_fileline " &
        '     " WHERE brgak_filename = @brgak_filename AND (brgak_fileline='' OR brgak_fileline=@brgak_fileline)" &
        '  " End " &



        Dim cn As SqlConnection = VERAG_PROG_ALLGEMEIN.SQL.GetNewOpenConnectionADMIN
        'cn.ConnectionString = "Data Source=SQLGUIDE01.verag.ost.dmn;Initial Catalog=ADMIN;Integrated Security=false;User ID=AppUser;Password=yp/THDd?xM+pZ$;"
        'cn.Open()
        Using cn
            Using cmd As New SqlCommand(sql, cn)
                cmd.Parameters.AddWithValue("@brgak_datum", brgak_datum)
                cmd.Parameters.AddWithValue("@brgak_betrag", brgak_betrag)
                cmd.Parameters.AddWithValue("@brgak_brgaktoId", brgak_brgaktoId)
                cmd.Parameters.AddWithValue("@brgak_filename", brgak_filename)
                cmd.Parameters.AddWithValue("@brgak_atc", brgak_atc)
                cmd.Parameters.AddWithValue("@brgak_fileline", brgak_fileline)
                Try
                    cmd.ExecuteNonQuery()

                    ''Lösche File: --> vom ALTEN ATLAS
                    'Try
                    '    If brgak_filename <> "DY" Then System.IO.File.Delete(frmRoutineManager.PathATLAS & "\" & brgak_filename)
                    'Catch ex As Exception
                    '    writeLog("ERROR", "Fehler beim Löschen der Aufschub-Datei: " & ex.Message)
                    'End Try
                    Return True
                Catch ex As SqlException
                    writeLog("ERROR", "Fehler beim Schreiben in die Datenbank: " & ex.Message)
                End Try
            End Using
        End Using
        cn.Close()
        Return False
    End Function


    Public Sub writeLog(typ, msg)
        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(typ, msg, System.Reflection.MethodBase.GetCurrentMethod.Name)
        Exit Sub
        'PROBE


        If Not System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "log\") Then
            System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory & "log\")
        End If
        Try
            Using sr As New StreamWriter(AppDomain.CurrentDomain.BaseDirectory & "log\err.log", True)
                sr.WriteLine(Now.ToString("dd.MM.yyyy HH:mm:ss") & ";" & typ & ";" & msg)
            End Using
        Catch ex As Exception
        End Try
    End Sub
    Sub writeLogVerarbeitet(datei)
        If Not System.IO.Directory.Exists(AppDomain.CurrentDomain.BaseDirectory & "log\") Then
            System.IO.Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory & "log\")
        End If
        Try
            Using sr As New StreamWriter(AppDomain.CurrentDomain.BaseDirectory & "log\worker.log", True)
                sr.WriteLine(Now.ToString("dd.MM.yyyy HH:mm:ss") & ";" & datei & " wurde verarbeitet.")
            End Using
        Catch ex As Exception
        End Try
    End Sub

End Module
