Imports System.IO
Imports System.Reflection
Imports System.Security.Cryptography
Imports System.Text.RegularExpressions
Imports System.Xml
Imports DigitalData.Modules
Imports DigitalData.Modules.Database
Imports DigitalData.Modules.Interfaces
Imports DigitalData.Modules.Jobs
Imports DigitalData.Modules.Jobs.ImportZUGFeRDFiles
Imports DigitalData.Modules.Logging

Public Class Form1
    Private _logConfig As LogConfig
    Private _firebird As Firebird
    Private _mssql As MSSQLServer
    Private _zugferd As ZUGFeRDInterface

    Private PropertyMap As New Dictionary(Of String, XmlItemProperty)


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        _logConfig = New LogConfig(LogConfig.PathType.CustomPath, Application.StartupPath & "\Log", Nothing, My.Application.Info.CompanyName, My.Application.Info.ProductName)
        _logConfig.Debug = True
        _firebird = New Firebird(_logConfig, My.Settings.FB_DATASOURCE, My.Settings.FB_DATABASE, My.Settings.FB_USER, My.Settings.FB_PASS)
        _mssql = New MSSQLServer(_logConfig, My.Settings.MSSQL_CONNECTIONSTRING)

        _zugferd = New ZUGFeRDInterface(_logConfig, "21182889975216572111813147150675976632")
    End Sub

    Private Function LoadFolderConfig(args As WorkerArgs)
        Dim oSQL As String = "SELECT T1.FOLDER_TYPE, T.FOLDER_PATH FROM TBEDM_FOLDER T, TBEDM_FOLDER_TYPE T1 WHERE T.FOLDER_TYPE_ID = T1.GUID AND T1.""ACTIVE"" = True AND T.""ACTIVE"" = True"
        Dim oResult As DataTable = _firebird.GetDatatable(oSQL)

        For Each row As DataRow In oResult.Rows
            Dim oFolderType = row.Item("FOLDER_TYPE")

            Select Case oFolderType
                Case ZUGFERD_IN
                    args.WatchDirectories.Add(row.Item("FOLDER_PATH"))

                Case ZUGFERD_SUCCESS
                    args.SuccessDirectory = row.Item("FOLDER_PATH")

                Case ZUGFERD_ERROR
                    args.ErrorDirectory = row.Item("FOLDER_PATH")

                Case ZUGFERD_EML
                    args.OriginalEmailDirectory = row.Item("FOLDER_PATH")

                Case ZUGFERD_REJECTED_EML
                    args.RejectedEmailDirectory = row.Item("FOLDER_PATH")

                Case ZUGFERD_ATTACHMENTS
                    args.AttachmentsSubDirectory = row.Item("FOLDER_PATH")
            End Select
        Next

        Return args
    End Function

    Private Function LoadPropertyMapFor(Args As WorkerArgs, Specification As String)
        Dim oSQL As String = $"SELECT * FROM TBEDM_XML_ITEMS WHERE SPECIFICATION = '{Specification}' AND ACTIVE = True ORDER BY XML_PATH"
        Dim oResult As DataTable = _firebird.GetDatatable(oSQL)

        For Each oRow As DataRow In oResult.Rows
            Dim xmlPath = oRow.Item("XML_PATH")
            Dim tableName = oRow.Item("TABLE_NAME")
            Dim tableColumn = oRow.Item("TABLE_COLUMN")
            Dim description = oRow.Item("DESCRIPTION")
            Dim isRequired = oRow.Item("IS_REQUIRED")
            Dim isGrouped = oRow.Item("IS_GROUPED")
            Dim groupScope = oRow.Item("GROUP_SCOPE")

            Args.PropertyMap.Add(xmlPath, New XmlItemProperty() With {
                .Description = description,
                .TableName = tableName,
                .TableColumn = tableColumn,
                .IsRequired = isRequired,
                .IsGrouped = isGrouped,
                .GroupScope = groupScope
            })
        Next

        Return Args
    End Function

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim args As New WorkerArgs() With {
            .MaxAttachmentSizeInMegaBytes = 10,
            .IgnoreRejectionStatus = False,
            .NamePortal = "TEST FROM FORM"
        }
        args = LoadFolderConfig(args)
        args = LoadPropertyMapFor(args, "DEFAULT")
        args.InsertIntoSQLServer = True

        Dim job As New Jobs.ImportZUGFeRDFiles(_logConfig, _firebird, 1, "TEST", _mssql)

        job.Start(args)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim oResult = OpenFileDialog1.ShowDialog()
        Dim oArgs As New WorkerArgs()

        If oResult = DialogResult.OK Then
            Dim oDoc = _zugferd.ValidateZUGFeRDFileWithGDPicture(OpenFileDialog1.FileName)
            Dim oZUGFERD = _zugferd.SerializeZUGFeRDDocument(oDoc)
            Console.WriteLine()

        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim oResult = OpenFileDialog1.ShowDialog()
        Dim oArgs As New WorkerArgs()
        oArgs = LoadPropertyMapFor(oArgs, "DEFAULT")

        If oResult = DialogResult.OK Then
            Dim oDoc = _zugferd.ValidateZUGFeRDFileWithGDPicture(OpenFileDialog1.FileName)
            Dim oZUGFERD = _zugferd.SerializeZUGFeRDDocument(oDoc)
            Console.WriteLine()

            Dim oResult2 = _zugferd.PropertyValues.CheckPropertyValues(oZUGFERD, oArgs.PropertyMap, "test")

            Console.WriteLine()
        End If
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        My.Settings.Save()
        Dim result = checkMD5(txtMD5Checksum.Text)
        If IsNothing(result) Then
            MsgBox("Could not calculate MD5 Checksum")
        Else
            txtMD5Checksum.Text = result
        End If
    End Sub
    Public Function checkMD5(ByVal filename As String) As String
        Try
            Dim MD5 As New MD5CryptoServiceProvider
            Dim Hash As Byte()
            Dim Result As String = ""
            Dim Tmp As String = ""

            Dim FN As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 8192)
            MD5.ComputeHash(FN)
            FN.Close()

            Hash = MD5.Hash
            Result = Strings.Replace(BitConverter.ToString(Hash), "-", "")
            Return Result
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Process.Start("\\dd-sto01\DD-DFSR01\SharedObjects\Public\Projekte\Test\Import\ZUGFerD\Email_in")
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Dim oResult = OpenFileDialog1.ShowDialog()

        If oResult = DialogResult.OK Then
            Dim oDoc = _zugferd.ValidateZUGFeRDFileWithGDPicture(OpenFileDialog1.FileName)
            Dim oZUGFERD = _zugferd.SerializeZUGFeRDDocument(oDoc)
            Dim oPropName As String = txtPropName.Text

            Try
                Dim oExtractor = New PropertyValues(_logConfig)
                Dim oValue As List(Of Object) = oExtractor.GetPropValue(oZUGFERD, oPropName)
                Dim oFinalValue As List(Of Object) = oExtractor.GetFinalPropValue(oValue)
                Console.WriteLine()

            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        Dim oExtractor = New PDFEmbeds(_logConfig)
        Dim oResult = OpenFileDialog1.ShowDialog()
        Dim oExtensions = New List(Of String) From {"docx", "doc", "pdf", "xls", "xlsx", "ppt", "pptx", "txt", "xml"}

        If oResult = DialogResult.OK Then
            oExtractor.Extract(OpenFileDialog1.FileName, AllowedExtensions:=oExtensions)
        End If
    End Sub
End Class
