Imports System.IO
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Logging

Public Class Form1
    Private MsgIds As New List(Of String)
    Public oMSSQL As MSSQLServer
    Public oFirebird As Firebird
    Public oLogConfig As LogConfig
    Public oLogger As Logger

    Public ExistingIds As Integer
    Public MissingIds As Integer
    Public FailedIds As Integer

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        oLogConfig = New LogConfig(LogConfig.PathType.CustomPath, Application.StartupPath)
        oLogger = oLogConfig.GetLogger

        ToolStripComboBox1.SelectedIndex = 0

        Try
            oMSSQL = New MSSQLServer(oLogConfig, My.Settings.MSSQL_CONNECTION_STRING)
            oFirebird = New Firebird(oLogConfig, My.Settings.FB_DATASOURCE, My.Settings.FB_DATABASE, My.Settings.FB_USERNAME, My.Settings.FB_PASSWORD)

            Dim oFilename As String = "zugferdhistory.txt"
            Dim oPath As String = Path.Combine(Application.StartupPath, oFilename)

            If File.Exists(oPath) = False Then
                Throw New Exception($"{oFilename} does not exist!!")
            End If

            MsgIds = File.ReadAllLines(oFilename).ToList

            AddLog($"{MsgIds.Count} MessageIDs added!")

        Catch ex As Exception
            oLogger.Error(ex)
            MsgBox("Error: " & vbNewLine & ex.Message, MsgBoxStyle.Critical, Text)
        End Try
    End Sub

    Private Sub AddLog(Message As String)
        oLogger.Info(Message)
        ListBox1.Items.Add(Message)
        ListBox1.SelectedIndex = ListBox1.Items.Count - 1

    End Sub

    Private Sub BringTheActionToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BringTheActionToolStripMenuItem.Click
        If ToolStripComboBox1.Text = "DELETE" Then
            Dim oResult = MsgBox("Action is set to DELETE! Do you want to continue?", MsgBoxStyle.YesNo, "Attention")

            If oResult = MsgBoxResult.Yes Then
                DoIt()
            Else
                MsgBox("Coward!")
            End If

        Else
            DoIt()
        End If
    End Sub

    Private Sub DoIt()
        For Each oMessageId As String In MsgIds
            Try
                Dim oSQL As String = $"SELECT msgid FROM VWCUST_BELEGE_TODAY WHERE msgid = '{oMessageId}'"
                Dim oResult As DataTable = oMSSQL.GetDatatable(oSQL)

                If oResult Is Nothing Then
                    Throw New Exception($"Nothing found in VWCUST_BELEGE_TODAY for message id [{oMessageId}]")
                End If

                AddLog($"rows for messageid [{oMessageId}]: [{oResult.Rows.Count}]")

                If oResult.Rows.Count = 0 Then
                    AddLog("No rows found, deleting from FB history.")
                    ' Delete from fb history 

                    oSQL = $"DELETE FROM TBEDM_ZUGFERD_HISTORY_IN WHERE MESSAGE_ID = '{oMessageId}'"
                    If ToolStripComboBox1.Text = "DELETE" Then

                        If oFirebird.ExecuteNonQuery(oSQL) = True Then
                            AddLog("Delete successful!")

                        End If
                    Else
                        AddLog("Simulating Delete !")
                        AddLog(oSQL)
                    End If

                    MissingIds += 1
                Else
                    AddLog("Rows found, all good!")
                    ExistingIds += 1
                End If
            Catch ex As Exception
                oLogger.Warn("Error while checking existence of MessageId [{0}]: {1}", oMessageId, ex.Message)
                oLogger.Error(ex)
                FailedIds += 1
            End Try
        Next

        AddLog("MissingIds: " & MissingIds)
        AddLog("ExistingIds: " & ExistingIds)
        AddLog("FailedIds: " & FailedIds)
    End Sub
End Class
