Imports System.Text

Public Class frmParkzeitImport

    Dim LIST As New List(Of VERAG_PROG_ALLGEMEIN.cParkzeiten)
    Dim validationResult As Boolean = False
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL


    Private Sub doImport()

        Dim fd As New OpenFileDialog
        fd.Filter = "CSV|*.csv;"
        fd.RestoreDirectory = True
        fd.Title = "CSV auswählen"
        fd.FilterIndex = 2

        Dim result As DialogResult = fd.ShowDialog()

        If result = System.Windows.Forms.DialogResult.OK And fd.FileName <> "" Then
            Try
                Me.Cursor = Cursors.WaitCursor
                LIST = Einlesen(fd.FileName)
                If LIST.Count > 0 Then
                    doValidation(LIST)
                End If
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try
        Else
            Me.Close()
        End If

        If validationResult Then
            Button1.BackColor = Color.LightGreen
        Else
            Button1.BackColor = Color.LightPink
        End If
        Me.Cursor = Cursors.Default
    End Sub

    Function saveList(LIST As List(Of VERAG_PROG_ALLGEMEIN.cParkzeiten)) As Boolean
        ProgressBar1.Minimum = 1
        ProgressBar1.Maximum = LIST.Count
        For Each P In LIST

            '   MsgBox(P.Kennzeichen)
            P.INSERT_EXISTS()
            ProgressBar1.PerformStep()

        Next
        ProgressBar1.Value = 1
        Return True
    End Function
    Function doValidation(LIST As List(Of VERAG_PROG_ALLGEMEIN.cParkzeiten)) As Boolean
        Dim cnt = 1
        ProgressBar1.Minimum = 1
        ProgressBar1.Maximum = LIST.Count
        validationResult = True
        For Each P In LIST
            P.Kennzeichen = SQL.DLookup("KfzKennzeichen", "SDL", " SDLNr=502 And KartenNr='" & P.KartenNr & "' ", "SDL", "").ToString
            P.KundenNr = SQL.DLookup("KundenNr", "SDL", " SDLNr=502 And KartenNr='" & P.KartenNr & "' ", "SDL", "").ToString
            If P.Kennzeichen = "" Then
                validationResult = False
            End If
            If P.KundenNr Is Nothing OrElse P.KundenNr.ToString = "" Then
                validationResult = False
            End If

            DataGridView1.Rows.Add(cnt, P.KartenNr, P.Kennzeichen, P.KundenNr)
            cnt += 1
            ProgressBar1.PerformStep()
            If cnt > 100 Then
                If cnt Mod 100 = 0 Then Me.Refresh()
            Else
                If cnt Mod 10 = 0 Then Me.Refresh()
            End If
        Next
        ProgressBar1.Value = 1
        Return True
    End Function


    Function Einlesen(FileName As String) As List(Of VERAG_PROG_ALLGEMEIN.cParkzeiten)
        Dim LIST As New List(Of VERAG_PROG_ALLGEMEIN.cParkzeiten)

        Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(FileName, Encoding.UTF8)
            MyReader.TextFieldType = FileIO.FieldType.Delimited
            MyReader.SetDelimiters(";")
            Dim currentRow As String()

            Dim cnt = 0
            If True Then
                Dim nextRead = False

                While Not MyReader.EndOfData
                    Try
                        currentRow = MyReader.ReadFields()


                        If currentRow(0) = "Kartennr." Then
                            nextRead = True

                        ElseIf nextRead Then
                            If currentRow(0) = "Summe" Then Exit While 'ENDE!
                            If currentRow(0) IsNot Nothing AndAlso currentRow(0) <> "" AndAlso IsNumeric(currentRow(0)) Then

                                Dim PARKZEIT As New VERAG_PROG_ALLGEMEIN.cParkzeiten


                                PARKZEIT.KartenNr = SQL.isleernothing(currentRow(0)).ToString
                                PARKZEIT.Bereich = SQL.isleernothing(currentRow(1)).ToString
                                PARKZEIT.Dauer_Minuten = CInt(SQL.isleernothing(currentRow(5)))

                                Dim totalHours = Math.Floor(PARKZEIT.Dauer_Minuten / 60)
                                Dim minutes = PARKZEIT.Dauer_Minuten Mod 60
                                PARKZEIT.Dauer = $"{CInt(totalHours):D2}:{CInt(minutes):D2}"

                                'PARKZEIT.Dauer = Minutes2Time(PARKZEIT.Dauer_Minuten).ToString("hh\:mm")

                                PARKZEIT.TarifArt = "VERAG"
                                PARKZEIT.KartenNr = SQL.isleernothing(currentRow(0)).ToString

                                If currentRow(3).ToString.Length > 0 Then
                                    Dim datumParse = DateTime.ParseExact(currentRow(3).Replace("  ", " "), "dd.MM.yyyy HH:mm", Nothing)
                                    PARKZEIT.Von = datumParse
                                    PARKZEIT.Bis = PARKZEIT.Von.AddMinutes(PARKZEIT.Dauer_Minuten)
                                End If



                                LIST.Add(PARKZEIT)
                            End If

                        End If


                        cnt += 1


                    Catch ex As Exception
                        VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace & vbNewLine & "Datei: " & FileName, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                    End Try
                End While

                'read_Detail = "Zeilen: " & cnt
            End If
        End Using

        Return LIST
    End Function
    Private Function Minutes2Time(ByVal minutes As Integer) As TimeSpan
        Return New TimeSpan(0, 0, minutes, 0, 0)
    End Function




    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Cursor = Cursors.WaitCursor
        Try

            If Not validationResult Then
                If vbYes <> MsgBox("Es gab Validierungsfehler, soll trotzdem Importiert werden?", vbYesNoCancel) Then
                    Me.DialogResult = DialogResult.None
                    Me.Cursor = Cursors.Default
                    Exit Sub
                End If
            End If
            If Not saveList(LIST) Then
                Me.DialogResult = DialogResult.None

            End If

        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Cursor = Cursors.Default

    End Sub

    Private Sub frmParkzeitImport_Load(sender As Object, e As EventArgs) Handles Me.Load

    End Sub

    Private Sub frmParkzeitImport_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        doImport()
    End Sub
End Class