Imports System.ComponentModel
Imports System.IO
Imports DD_LIB_Standards

Public Class frmVersionCheck
    Private InitSteps As Integer = 6
    Private bw As New BackgroundWorker()
    Private mainForm As Form
    Private UPDATE_NECESSARY As Boolean = False
    Private UPDATE_CANCELLED As Boolean = False
    Private Sub InitProgram()
        bw.WorkerReportsProgress = True
        AddHandler bw.DoWork, AddressOf bw_DoWork
        AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
        AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted

        ' mainForm = My.Forms.frmMain

        bw.RunWorkerAsync()
    End Sub

    Private Function CalcProgress(_step As Integer)
        Return _step * (100 / InitSteps)
    End Function
    Private Sub bw_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
        Try
            Dim JUMP_UPDATE As Boolean = False
            'Try
            Dim Init = New ClassInit()
            bw.ReportProgress(CalcProgress(1), "Initializing Logger")
            Init.InitLogger()
            System.Threading.Thread.Sleep(200)
            bw.ReportProgress(CalcProgress(3), "Initializing MySettings")
            MySettings_Load()
            System.Threading.Thread.Sleep(200)
            bw.ReportProgress(CalcProgress(2), "Initializing Database")
            If Init.InitDatabase() = True Then
                System.Threading.Thread.Sleep(200)
                bw.ReportProgress(CalcProgress(3), "Initializing Basic-Configuration")
                Init.InitBasics()
                System.Threading.Thread.Sleep(200)
                bw.ReportProgress(CalcProgress(4), "Initializing User-Configuration")
                If ClassInit.InitUser = False Then
                    Exit Sub
                Else
                    VERSION_USER = CInt(VERSION_USER.ToString.Replace(".", ""))
                    VERSION_SERVER = CInt(VERSION_SERVER.ToString.Replace(".", ""))
                    If (VERSION_USER = VERSION_SERVER) Or VERSION_SERVER = 1000 Or VERSION_USER = 1000 Then
                        Exit Sub
                    End If
                    UPDATE_NECESSARY = True
                    If FORCE_UPDATE = False Then
                        If VERSIONS_FOR_FORCE_UPDATE.Contains(VERSION_USER) Then
                            ClassInit.InsertEssential_Log(USER_GUID, "USER-ID", String.Format("VersionChecker: ForceUpdate for User as Version '{0}' is used!", VERSION_USER))
                            FORCE_UPDATE = True
                        End If
                    End If
                    If FORCE_UPDATE = False Then
                        Dim msg = "Auf dem Server liegt ein Update für ADDI bereit!" & vbNewLine & "Wollen Sie das Update nun durchführen? Die Dauer ist abhängig von Ihrer Netzwerkverbindung!"
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "There is a new release available for ADDI!" & vbNewLine & "Would You like to install the update now? This might take some minutes!"
                        End If
                        Dim result As MsgBoxResult
                        result = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                        If result = MsgBoxResult.No Then
                            UPDATE_CANCELLED = True
                            Exit Sub
                        End If
                    End If

                    If MyServer_UpdatePath <> String.Empty Then
                        If Directory.Exists(MyServer_UpdatePath) Then
                            GetTempFolderGuid()
                            If FOLDER_TEMP <> String.Empty Then
                                bw.ReportProgress(CalcProgress(5), "Copying files to tempfolder")
                                ' Make a reference to a directory.
                                Dim di As New DirectoryInfo(MyServer_UpdatePath)
                                ' Get a reference to each file in that directory.
                                Dim fiArr As FileInfo() = di.GetFiles()
                                ' Display the names of the files.
                                'Dim fri As FileInfo
                                Dim error_while_copying = False
                                For Each Upd_item As DataRow In DT_UPDATE_ITEMS.Rows
                                    If error_while_copying = True Then
                                        Exit For
                                    End If
                                    Dim updatefile2copy = Path.Combine(MyServer_UpdatePath, Upd_item.Item("ITEM_INFO"))
                                    Dim tempfilename = Path.Combine(FOLDER_TEMP, Upd_item.Item("ITEM_INFO"))
                                    If File.Exists(updatefile2copy) Then
                                        Try
                                            System.IO.File.Copy(updatefile2copy, tempfilename)
                                        Catch ex As Exception
                                            ClassLogger.Add(String.Format("Error while copying file {0} to {1}: " & ex.Message, updatefile2copy, tempfilename))
                                            error_while_copying = True
                                        End Try
                                    Else
                                        ClassLogger.Add(String.Format("UpdateFile {0} is not existing or accessible", updatefile2copy))
                                    End If
                                Next

                                If error_while_copying = False Then
                                    Replace_Files()
                                End If

                                Try
                                    'Delete the tempfolder and all data
                                    System.IO.Directory.Delete(FOLDER_TEMP, True)
                                Catch ex As Exception

                                End Try
                            Else
                                ClassLogger.Add(String.Format("The temporaryFolder could not be created!"))
                            End If
                        Else
                            ClassLogger.Add(String.Format("The Updatepath '{0}'is not accessible or does not exist", MyServer_UpdatePath))
                        End If
                    Else
                        ClassLogger.Add(String.Format("NO ACTION: the Updatepath is empty"))
                    End If
                End If

            Else
                ClassLogger.Add(String.Format(">> Database was not intialized!"), False)
            End If
        Catch ex As Exception
            ClassLogger.Add(String.Format(">> Unexpected Error in bwDoWork: " & ex.Message))
            ClassLogger.Add(ex.StackTrace)
        End Try
    End Sub
    Sub Replace_Files()
        Try
         
            'Jede Datei im tempfolder wird replaced
            Dim di As New DirectoryInfo(FOLDER_TEMP)
            ' Get a reference to each file in that directory.
            Dim fiArr As FileInfo() = di.GetFiles()
            ' Display the names of the files.
            ' Dim fri As FileInfo
            Dim error_while_replacing = False
            For Each Upd_item As DataRow In DT_UPDATE_ITEMS.Rows
                Dim BackUpOfFileToReplace As String = MY_INSTALL_PATH & "\" & Upd_item.Item("ITEM_INFO") & ".bac"
                Dim sourcefile = Path.Combine(FOLDER_TEMP, Upd_item.Item("ITEM_INFO"))
                Dim targetfile
                If IsDBNull(Upd_item.Item("INFO1")) Then
                    targetfile = Path.Combine(MY_INSTALL_PATH, Upd_item.Item("ITEM_INFO"))
                Else
                    If Upd_item.Item("INFO1") <> String.Empty Then
                        targetfile = Path.Combine(MY_INSTALL_PATH, Upd_item.Item("INFO1"), Upd_item.Item("ITEM_INFO"))
                    Else
                        targetfile = Path.Combine(MY_INSTALL_PATH, Upd_item.Item("ITEM_INFO"))
                    End If
                End If

                Try
                    ' Replace the file.
                    If File.Exists(targetfile) Then
                        If File_Rename(targetfile, BackUpOfFileToReplace) = True Then
                            If MoveFile(sourcefile, targetfile) = True Then
                                File_Delete(BackUpOfFileToReplace)
                            Else
                                'Verschieben hat nicht geklappt also die Backupdatei wieder umbenennen!
                                File_Rename(BackUpOfFileToReplace, targetfile)
                            End If
                        End If
                    Else
                        MoveFile(sourcefile, targetfile)
                    End If


                Catch ex As Exception
                    ClassLogger.Add(String.Format("Error while copying file {0} to {1}: " & ex.Message, sourcefile, targetfile))
                    error_while_replacing = True
                End Try
            Next
            'For Each fri In fiArr
            '    If error_while_replacing = True Then
            '        Exit For
            '    End If
            '    Dim no_work = False
            '    For Each row As DataRow In DTEXCLUDE_FILES.Rows
            '        Dim content As String = row.Item(0).ToString.ToLower
            '        If fri.Name.Contains(content) Then
            '            no_work = True
            '        End If
            '    Next
            '    If no_work = False Then 'Copy the file to tempFolder
            '        Try
            '            Dim BackUpOfFileToReplace As String = REPLACE_RO_PATH & "\" & fri.Name & ".bac"
            '            ' Replace the file.
            '            Dim sourcefile = fri.FullName
            '            Dim targetfile = REPLACE_RO_PATH & "\" & fri.Name
            '            If File.Exists(targetfile) Then
            '                If File_Rename(targetfile, BackUpOfFileToReplace) = True Then
            '                    If MoveFile(sourcefile, targetfile) = True Then
            '                        File.Delete(BackUpOfFileToReplace)
            '                    Else
            '                        File_Rename(BackUpOfFileToReplace, targetfile)
            '                    End If
            '                End If
            '            Else
            '                MoveFile(sourcefile, targetfile)
            '            End If


            '        Catch ex As Exception
            '            ClassLogger.Add(String.Format("Error while copying file {0} to {1}: " & ex.Message, fri.FullName, Path.Combine(FOLDER_TEMP, fri.Name)))
            '            error_while_replacing = True
            '        End Try
            '    End If
            '    Console.WriteLine(fri.Name)
            'Next fri
        Catch ex As Exception
            ClassLogger.Add(String.Format("Unexpected Error in Replace_Files: {0}", ex.Message))
        End Try
    End Sub
    Private Shared Function File_Rename(targetfile As String, BackUpOfFileToReplace As String)
        Try
            If File.Exists(BackUpOfFileToReplace) Then
                If File_Delete(BackUpOfFileToReplace) = False Then
                    Return False
                End If
            End If
            Rename(targetfile, BackUpOfFileToReplace)
            Return True
        Catch ex As Exception
            ClassLogger.Add(String.Format("Unexpected Error in File_Rename: " & vbNewLine & "targetfile '{0}'" & vbNewLine & "BackUpOfFileToReplace '{1}'" & vbNewLine & "ERROR: {2}", targetfile, BackUpOfFileToReplace, ex.Message))
            Return False
        End Try
    End Function
    Private Shared Function File_Delete(deletefile As String)
        Try
            File.Delete(deletefile)
            Return True
        Catch ex As Exception
            ClassLogger.Add(String.Format("Unexpected Error in File_Delete: " & vbNewLine & "deletefile '{0}'" & vbNewLine & "ERROR: {2}", deletefile, ex.Message))
            Return False
        End Try
    End Function
    Private Shared Function MoveFile(sourcefile As String, targetfile As String)
        Try
            File.Move(sourcefile, targetfile)
            Return True
        Catch ex As Exception
            ClassLogger.Add(String.Format("Unexpected Error in MoveFile: sourcefile '{0}', targetfile '{1}' - ERROR: {2}", sourcefile, targetfile, ex.Message))
            Return False
        End Try
    End Function
    Sub Start_RO()
        Dim filename = ""
        Try
            Dim PMO_PATH = System.IO.Path.Combine(MY_INSTALL_PATH, "DD-Record-Organizer.exe")
            Dim startInfo As New ProcessStartInfo()
            startInfo.Arguments = """" & MyConnectionString & """"
            filename = startInfo.FileName

            If System.IO.File.Exists(PMO_PATH) Then
                startInfo.FileName = PMO_PATH
                Process.Start(startInfo)
            Else
                MsgBox("Can not find ADDI-Executable in '" & filename & "'! Please inform your systemadmin.", MsgBoxStyle.Critical)
            End If
          
        Catch ex As Exception
            ClassLogger.Add("Could not find RecordOrganizer: " & filename & " - " & ex.Message)
        End Try

    End Sub
    Private Function GetTempFolderGuid() As String
        Try
            Dim folder As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString)
            If Not Directory.Exists(folder) Then
                Directory.CreateDirectory(folder)
            End If
            FOLDER_TEMP = folder
        Catch ex As Exception
            ClassLogger.Add(String.Format("Error while Creating tempfolder: " & ex.Message))
        End Try

    End Function

    Private Sub frmVersionCheck_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        If ERROR_WHILE_UPDATING = True Then
            Dim msg = String.Format("Während des Updatevorgangs für Version '{0}' haben sich unerwartet Fehler ereignet!" & vbNewLine & "Wollen Sie die Logdatei anzeigen?", VERSION_SERVER)
            If USER_LANGUAGE <> "de-DE" Then
                msg = String.Format("During update of version '{0}' unexpected errors occured!" & vbNewLine & "Would You like to show the logfile?", VERSION_SERVER)
            End If
            ClassInit.InsertEssential_Log(USER_GUID, "USER-ID", String.Format("Unexpected errors occured during client-update update of version {0}!", VERSION_SERVER))
            Dim result As MsgBoxResult
            result = MessageBox.Show(msg, "Confirmation:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(ClassLogger.DateiSpeicherort)
            End If
        Else
            If UPDATE_NECESSARY = True Then
                If UPDATE_CANCELLED = True Then
                    If clsDatabase.DB_DEFAULT_INITIALIZED = True Then
                        ClassInit.InsertEssential_Log(USER_GUID, "USER-ID", String.Format("The ClientUpdate {0} is necessary but user cancelled update-process!", VERSION_SERVER))
                    End If
                Else
                    If clsDatabase.DB_DEFAULT_INITIALIZED = True Then
                        ClassInit.InsertEssential_Log(USER_GUID, "USER-ID", String.Format("The ClientUpdate  {0} was completed without errors!", VERSION_SERVER))
                    End If
                End If
                
            End If
        End If
        
        Start_RO()
    End Sub
    Private Sub frmVersionCheck_Load(sender As Object, e As EventArgs) Handles Me.Load
        InitProgram()
    End Sub
    Private Sub bw_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs)
        pbStatus.Value = e.ProgressPercentage
        lblStatus.Text = e.UserState.ToString()
    End Sub

    Private Sub bw_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
        Me.Close()
    End Sub
End Class
