Imports System.Console
Imports System.IO
Imports System.Xml
Imports NLog

Module Main
    Public LOGPATH As String

    ' Config Variablen
    'Dim username As String '= "TestBrainpool"
    'Dim password As String '= "09Test2015"
    'Dim filename As String '= "BRAINPOOL_MARKEN.xml"
    'Dim query As String '= "INH=""BRAINPOOL"""
    'Dim connstring As String
    'Dim database As String

    Private logger As Logger = LogManager.GetLogger("Main")

    Dim mainDoc As XmlDocument
    Dim markDoc As XmlDocument

    Dim MainFile As String = "Importer-SearchData.xml"

    Dim p As New Parser()
    Dim dpma As DPMAConnect
    Dim db As DB

    Dim config As ConfigValues
    Dim marks As New List(Of Mark)
    Dim props = New List(Of String) From {
            "RegistrationOfficeCode",
            "RegistrationDate",
            "RegistrationNumber",
            "MarkCurrentStatusCode",
            "MarkVerbalElementText",
            "MarkFeature",
            "ApplicationDate",
            "Applicant",
            "Representative",
            "PublicationDate",
            "ExpiryDate",
            "TerminationDate",
            "OppositionPeriodStartDate",
            "OppositionPeriodEndDate",
            "Classification",
            "ClassificationLong"
        }

    Sub Main()
        Try
            config = AppConfig.GetConfiguration()

            logger.Info("{0} started", My.Application.Info.Title)

            ' Abfrage starten
            logger.Info("Sending request with query: {0}", config.query)
            dpma = New DPMAConnect(config.username, config.password)
            mainDoc = dpma.Search(config.query)
            mainDoc.Save(MainFile)

            ' Ergebnis auslesen und Marken-Klassen erstellen
            marks = p.ReadMarkXMLFile(MainFile)

            For Each mark As Mark In marks
                Dim akz As String = mark.ApplicationNumber
                Dim file As String = String.Format("Importer-RegisterData-{0}.xml", akz)

                logger.Info("Getting Register Info for {0}", akz)

                markDoc = dpma.GetRegisterInfo(akz)
                markDoc.Save(file)

                p.ReadMarkRegisterInfoXMLFile(file, mark)
                'p.ReadMarkRegisterInfoXML(markDoc, mark)
            Next

            logger.Info("{0} Marks imported", marks.Count)
            logger.Info("================================")

            ' =========================================================================================

            db = New DB(config.connstring, "DD_ECM")
            Dim formId As Integer = db.GetFormId()

            For Each m As Mark In marks

                Dim mainControlId As Integer

                ' Das eindeutige Control suchen
                mainControlId = db.GetControlId(formId)

                ' Über mainControlId überprüfen, ob marke vorhanden
                Dim markExists As Integer = db.GetRecordId(mainControlId, m.ApplicationNumber)

                ' Wenn noch nicht vorhanden
                If (markExists = 0) Then
                    ' Einen Record erstellen
                    Dim recordId = db.InsertRecord(formId)
                    logger.Info("New record created with GUID: " & recordId)
                    ' Den Leit-Wert einfügen für mainControlId
                    Dim valueId = db.InsertValue(mainControlId, recordId, m.ApplicationNumber)
                    logger.Info("Value inserted - Property: {0}, Value: {1}, ControlId: {2}", "ApplicationNumber", m.ApplicationNumber, mainControlId)

                    ' alle anderen properties zu dieser marke einfügen einfügen
                    For Each prop As String In props
                        ' ControlID für die aktuelle property holen
                        Dim controlId = db.GetControlId(formId, prop)
                        ' Wert für die aktuelle property holen
                        Dim value = db.GetProperty(m, prop)
                        ' Wert einfügen
                        db.InsertValue(controlId, recordId, value)
                        logger.Info("Value inserted - Property: {0}, Value: {1}, ControlId: {2}", prop, value, controlId)
                    Next
                Else
                    ' Marke aktualisieren
                    Dim recordId As Integer = markExists

                    For Each prop As String In props
                        ' ControlID für die aktuelle property holen
                        Dim controlId = db.GetControlId(formId, prop)
                        ' Wert für die aktuelle property holen
                        Dim value = db.GetProperty(m, prop)
                        ' Wert aktualisieren

                        Dim hasChanged As Boolean = Not db.IsEqual(controlId, recordId, value)

                        If hasChanged Then
                            db.UpdateValue(controlId, recordId, value)
                            logger.Info("Value updated - Property: {0}, NewValue: {1}, ControlId: {2}", prop, value, controlId)
                        End If
                    Next
                End If
                logger.Info("================================")
            Next


        Catch ex As Exception
            logger.Error("================================")
            logger.Error("An Error occurred: " & ex.Message)
            Environment.Exit(1)
        End Try

    End Sub

End Module
