Imports System.IO
Public Class ClassUpdate
    Public Shared MyServer_UpdatePath As String

    Public Shared VERSION_SERVER = "1.0.0.0"
    Public Shared VERSION_USER = "1.0.0.0"
    Public Shared FORCE_UPDATE As Boolean = False
    Public Shared UPDATE_ID As Integer
    Public Shared ALL_USERS As Boolean = False
    Public Shared VERSIONS_FOR_FORCE_UPDATE As String = ""
    Public Shared FOLDER_TEMP As String

    Public Shared MY_INSTALL_PATH As String
    Public Shared DT_UPDATE_ITEMS As DataTable
    Public Shared DT_UPDATE As DataTable
    Public Shared ERROR_WHILE_UPDATING As Boolean = False

    Public Shared UPDATE_NECESSARY As Boolean = False
    Public Shared UPDATE_CANCELLED As Boolean = False
    Public Shared UPDATE_ERROR As Boolean = False

    Private Shared RecExe_found As Boolean = False
    Public Shared DT_USER_DATA As DataTable
    Private Shared USER_INFO1, USER_INFO2, USER_INFO3 As String
    Public Shared Function Init()
        Try
            Dim sql = String.Format("SELECT * FROM TBDD_MODULES WHERE UPPER(NAME) = UPPER('Record-Organizer')")
            Dim KONFIG_DT As DataTable = MYDB_ECM.GetDatatable(sql)
            If KONFIG_DT.Rows.Count = 1 Then
                MyServer_UpdatePath = KONFIG_DT.Rows(0).Item("VERSION_UPATE_PATH")
                MIN_REQUIRED_VERSION = KONFIG_DT.Rows(0).Item("MIN_REQUIRED_VERSION")
                Try
                    DBVERSION = KONFIG_DT.Rows(0).Item("DB_VERSION")
                Catch ex As Exception
                    DBVERSION = "No DB Version-Config"
                End Try
            End If
            sql = String.Format("Select * FROM TBDD_VERSION_UPDATE WHERE GUID = (Select MAX(GUID) FROM TBDD_VERSION_UPDATE WHERE UPPER(MODULE_NAME) = UPPER('{0}'))", "Record-Organizer")
            DT_UPDATE = MYDB_ECM.GetDatatable(sql)
            If Not IsNothing(DT_UPDATE) Then
                If DT_UPDATE.Rows.Count = 1 Then
                    UPDATE_ID = DT_UPDATE.Rows(0).Item("GUID")
                    VERSION_SERVER = DT_UPDATE.Rows(0).Item("VERSION_NO")
                    FORCE_UPDATE = DT_UPDATE.Rows(0).Item("FORCE_UPD")
                    VERSIONS_FOR_FORCE_UPDATE = DT_UPDATE.Rows(0).Item("VERSION_FORCE_UPD")
                    ALL_USERS = DT_UPDATE.Rows(0).Item("ALL_USERS")
                    sql = String.Format("SELECT * FROM TBDD_VERSION_ITEMS WHERE UPDATE_ID = {0} AND [INFO1] IS NOT NULL ORDER BY GUID", UPDATE_ID)
                    DT_UPDATE_ITEMS = MYDB_ECM.GetDatatable(sql)
                    LOGGER.Info(String.Format("{0} items need to be updated!", DT_UPDATE_ITEMS.Rows.Count.ToString))
                Else
                    LOGGER.Info("No Updates Configured!")
                End If
            End If
            Return True
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in ClassUpdate - Init: " & ex.Message)
            Return False
        End Try

    End Function
    Public Shared Function InitInstallPath()
        Try
            Dim readValue = My.Computer.Registry.GetValue("HKEY_CURRENT_USER\Software\Digital Data\Record Organizer", "Path", Nothing)
            If Not IsNothing(readValue) Then
                MY_INSTALL_PATH = readValue
                Return True
            Else
                MY_INSTALL_PATH = ""
                For Each s In Directory.GetLogicalDrives()
                    If RecExe_found = False Then
                        DirSearch(s)
                    End If
                Next
                If RecExe_found = False Then
                    LOGGER.Warn("Could not find the path for RecordOrganizer")
                    Return False
                End If
            End If
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in InitInstallPath: " & ex.Message)
            Return False
        End Try
    End Function
    Private Shared Sub DirSearch(ByVal sDir As String)
        Dim d As String
        Dim f As String
        Try
            For Each d In Directory.GetDirectories(sDir)
                If d.Contains("$Recycle") = False Or d.Contains("System Volume") = False Then
                    If RecExe_found = False Then
                        For Each f In Directory.GetFiles(d, "DD-OrgFlow.exe")
                            RecExe_found = True
                            MY_INSTALL_PATH = Path.GetDirectoryName(f)
                            Exit Sub
                        Next
                    End If
                    If RecExe_found = False Then
                        DirSearch(d)
                    End If
                End If
            Next
        Catch excpt As System.Exception
            LOGGER.Warn("Unexpected Error in DirSearch: " & excpt.Message)
            MY_INSTALL_PATH = ""
        End Try
    End Sub
    Public Shared Function InitUser(Optional _User As String = "")
        Try
            Dim sql = ""
            USER_USERNAME = Environment.UserName
            sql = String.Format("SELECT * FROM TBDD_USER WHERE (LOWER(USERNAME) = LOWER('{0}'))", USER_USERNAME)
            Dim USER_DT As DataTable = MYDB_ECM.GetDatatable(sql)
            If USER_DT.Rows.Count = 0 Then
                LOGGER.Warn(" - User '" & USER_USERNAME & "' not listed in Useradministration!")
                'MsgBox("Achtung: Sie sind nicht in der Userverwaltung hinterlegt." & vbNewLine & "Bitte setzen Sie sich mit dem Systembetreuer in Verbindung!", MsgBoxStyle.Critical, "Achtung:")
                'Me.Close()
                Dim msg = String.Format("You are not listed in the Useradministration." & vbNewLine & "Please contact the admin.")
                MsgBox(msg, MsgBoxStyle.Exclamation)
                Return False
            Else
                USER_GUID = USER_DT.Rows(0).Item("GUID")
                USER_LANGUAGE = USER_DT.Rows(0).Item("LANGUAGE")
                sql = String.Format("SELECT UPDATE_PATH,TEMPPATH,INFO1,INFO2,INFO3 FROM TBDD_VERSION_USER_UPDATE_PATH WHERE USER_ID = {0} AND UPPER(MODULE_NAME) = UPPER('{1}')", USER_GUID, "Record-Organizer")
                DT_USER_DATA = MYDB_ECM.GetDatatable(sql)
                MyServer_UpdatePath = DT_USER_DATA.Rows(0).Item("UPDATE_PATH")

                sql = String.Format("SELECT CASE VERSION_CLIENT WHEN '' THEN '{3}' ELSE VERSION_CLIENT END AS VERSION_CLIENT FROM VWDD_LOGIN_USER_HISTORY WHERE GUID = (select MAX(GUID) from VWDD_LOGIN_USER_HISTORY where USER_ID = {0} AND VERSION_CLIENT <> '' AND UPPER(MACHINE_NAME) = UPPER('{1}') AND UPPER(MODULE) = UPPER('{2}'))", USER_GUID, Environment.MachineName, "Record-Organizer", VERSION_SERVER)
                VERSION_USER = MYDB_ECM.GetScalarValue(sql)
                If IsNothing(VERSION_USER) Then
                    sql = String.Format("SELECT CASE VERSION_CLIENT WHEN '' THEN '{2}' ELSE VERSION_CLIENT END AS VERSION_CLIENT FROM VWDD_LOGIN_USER_HISTORY WHERE GUID = (select MAX(GUID) from VWDD_LOGIN_USER_HISTORY where USER_ID = {0} AND VERSION_CLIENT <> '' AND UPPER(MODULE) = UPPER('{1}'))", USER_GUID, "Record-Organizer", VERSION_SERVER)
                    VERSION_USER = MYDB_ECM.GetScalarValue(sql)
                    If IsNothing(VERSION_USER) Then
                        VERSION_USER = "1.0.0.0"
                    End If
                End If
                VERSION_USER = CInt(VERSION_USER.ToString.Replace(".", ""))
                VERSION_SERVER = CInt(VERSION_SERVER.ToString.Replace(".", ""))
                Return True
            End If
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in InitUser_Update_Spec: " & ex.Message)
            Return False
        End Try

    End Function
    Public Shared Sub RUN_UPDATE()
        Dim UPD_VC As Boolean = False
        Dim UPD_RM As Boolean = False
        Dim KEEP_TEMPPATH As Boolean = False
        If DT_USER_DATA.Rows.Count <> 1 Then
            Exit Sub
        Else
            USER_INFO1 = DT_USER_DATA.Rows(0).Item("INFO1")
            USER_INFO2 = DT_USER_DATA.Rows(0).Item("INFO2")
            USER_INFO3 = DT_USER_DATA.Rows(0).Item("INFO3")

            If DT_USER_DATA.Rows(0).Item("TEMPPATH") <> "" Then
                FOLDER_TEMP = DT_USER_DATA.Rows(0).Item("TEMPPATH")
            Else
                For Each Upd_item As DataRow In DT_UPDATE_ITEMS.Rows
                    If Upd_item.Item("ITEM_INFO") = "VERSION_CHECKER.exe" Then
                        If Not USER_INFO1.Contains(Upd_item.Item("INFO2")) Then
                            UPD_VC = True

                        End If
                    ElseIf Upd_item.Item("ITEM_INFO") = "RecordOrganizer_RightManager.exe" Then
                        If Not USER_INFO1.Contains(Upd_item.Item("INFO2")) Then
                            UPD_RM = True
                        End If
                    End If
                    If Not IsDBNull(Upd_item.Item("INFO3")) Then
                        FOLDER_TEMP = Upd_item.Item("INFO3")
                    End If
                Next
            End If
        End If
        If UPD_VC = True Or UPD_RM = True Then
            UPDATE_NECESSARY = True
        End If

        If UPDATE_NECESSARY = False Then
            Exit Sub
        End If

        Dim msg = "Auf dem Server liegt ein Update für ein OrgFlow-AddOn 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 an OrgFlow-AddOn!" & vbNewLine & "Would You like to install the update now? This might take some time minute(s)!"
        End If
        Dim result As MsgBoxResult
        result = MessageBox.Show(msg, CAPTION_CONFIRMATION, MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.No Then
            UPDATE_CANCELLED = True
            Exit Sub
        End If
        'End If

        If FOLDER_TEMP <> String.Empty Then
            If Directory.Exists(FOLDER_TEMP) Then
                ' GetTempFolderGuid()
                ' If FOLDER_TEMP <> String.Empty Then

                Dim error_while_copying = False
                For Each Upd_item As DataRow In DT_UPDATE_ITEMS.Rows
                    LOGGER.Info(String.Format("...working on item {0}: ", Upd_item.Item("ITEM_INFO")))

                    If Upd_item.Item("ITEM_INFO") = "VERSION_CHECKER.exe" Then
                        KEEP_TEMPPATH = Upd_item.Item("BIT3")
                    End If

                    If error_while_copying = True Then
                        Exit For
                    End If
                    Dim tempfilename = Path.Combine(FOLDER_TEMP, Upd_item.Item("ITEM_INFO"))
                    If File.Exists(tempfilename) Then
                        Try
                            Dim error_while_replacing = False

                            Dim BackUpOfFileToReplace As String = MY_INSTALL_PATH & "\" & Upd_item.Item("INFO1") & Upd_item.Item("ITEM_INFO") & ".bac"
                            BackUpOfFileToReplace = BackUpOfFileToReplace.Replace("//", "/")

                            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
                            targetfile = targetfile.ToString.Replace("//", "/")
                            LOGGER.Info(String.Format("...replacing targetfile '{0}': ", targetfile))
                            Try
                                ' Replace the file.
                                If File.Exists(targetfile) Then
                                    If File_Rename(targetfile, BackUpOfFileToReplace) = True Then
                                        If File.Exists(BackUpOfFileToReplace) Then
                                            If KEEP_TEMPPATH Then
                                                If CopyFile(sourcefile, targetfile) = True Then
                                                    File_Delete(BackUpOfFileToReplace)
                                                    LOGGER.Warn(String.Format("...targetfile '{0}' was copied! ", targetfile))
                                                    Dim updinfo
                                                    If USER_INFO1 <> "" Then
                                                        updinfo = USER_INFO1 & ";" & Upd_item.Item("INFO1") & "V" & Upd_item.Item("INFO2")
                                                    Else
                                                        updinfo = Upd_item.Item("INFO1") & "V" & Upd_item.Item("INFO2")
                                                    End If
                                                    Dim _Sql = String.Format("Update TBDD_VERSION_USER_UPDATE_PATH SET INFO1 = '{2}' WHERE USER_ID = {0} AND UPPER(MODULE_NAME) = UPPER('{1}')", USER_GUID, "Record-Organizer", updinfo)
                                                    MYDB_ECM.ExecuteNonQuery(_Sql)
                                                End If
                                            Else
                                                If MoveFile(sourcefile, targetfile) = True Then
                                                    File_Delete(BackUpOfFileToReplace)
                                                    LOGGER.Info(String.Format("...targetfile '{0}' was replaced! ", targetfile))
                                                    Dim updinfo
                                                    If USER_INFO1 <> "" Then
                                                        updinfo = USER_INFO1 & ";" & Upd_item.Item("INFO1") & "V" & Upd_item.Item("INFO2")
                                                    Else
                                                        updinfo = Upd_item.Item("INFO1") & "V" & Upd_item.Item("INFO2")
                                                    End If
                                                    Dim _Sql = String.Format("Update TBDD_VERSION_USER_UPDATE_PATH SET INFO1 = '{2}' WHERE USER_ID = {0} AND UPPER(MODULE_NAME) = UPPER('{1}')", USER_GUID, "Record-Organizer", updinfo)
                                                    MYDB_ECM.ExecuteNonQuery(_Sql)
                                                Else
                                                    LOGGER.Warn(String.Format("MoveFile was not successfull! BackupFile will be activated!"))
                                                    'Verschieben hat nicht geklappt also die Backupdatei wieder umbenennen!
                                                    File_Rename(BackUpOfFileToReplace, targetfile)
                                                End If
                                            End If

                                        End If

                                    End If
                                Else

                                End If


                            Catch ex As Exception
                                LOGGER.Warn(String.Format("Error while copying file {0} to {1}: " & ex.Message, sourcefile, targetfile))
                                error_while_replacing = True
                                UPDATE_ERROR = True
                            End Try



                        Catch ex As Exception
                            LOGGER.Warn(String.Format("Unexpected Error in Replace_Files: {0}", ex.Message))
                            UPDATE_ERROR = True
                        End Try
                    End If

                Next

                Dim upd = String.Format("Update TBDD_VERSION_USER_UPDATE_PATH SET TEMPPATH = '' WHERE USER_ID = {0} AND UPPER(MODULE_NAME) = UPPER('{1}')", USER_GUID, "Record-Organizer")
                MYDB_ECM.ExecuteNonQuery(upd)
                Try
                    If KEEP_TEMPPATH = False Then
                        'Delete the tempfolder and all data
                        System.IO.Directory.Delete(FOLDER_TEMP, True)
                    Else
                        LOGGER.Info(String.Format("TEMP FOLDER SHALL BE KEPT..."))
                    End If

                Catch ex As Exception

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

    End Sub
    Private Shared 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
            LOGGER.Warn(String.Format("Error while Creating tempfolder: " & ex.Message))
        End Try

    End Function
    Private Shared Function File_Rename(targetfile As String, Renamefilestring As String)
        Try
            Renamefilestring = Renamefilestring.Replace("\\", "\")
            If File.Exists(Renamefilestring) Then

                If File_Delete(Renamefilestring) = False Then
                    Return False
                End If
            End If
            Rename(targetfile, Renamefilestring)
            Return True
        Catch ex As Exception
            LOGGER.Warn(String.Format("ClassUpdate - Unexpected Error in File_Rename: " & "OldPath '{0}'" & "NewPath '{1}'" & "ERROR: {2}", targetfile, Renamefilestring, ex.Message))
            UPDATE_ERROR = True
            Return False
        End Try
    End Function
    Private Shared Function File_Delete(deletefile As String)
        Try
            File.Delete(deletefile)
            Return True
        Catch ex As Exception
            LOGGER.Warn(String.Format("Unexpected Error in File_Delete: " & vbNewLine & "deletefile '{0}'" & vbNewLine & "ERROR: {2}", deletefile, ex.Message))
            UPDATE_ERROR = True
            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
            LOGGER.Warn(String.Format("Unexpected Error in MoveFile: sourcefile '{0}', targetfile '{1}' - ERROR: {2}", sourcefile, targetfile, ex.Message))
            UPDATE_ERROR = True
            Return False
        End Try
    End Function
    Private Shared Function CopyFile(sourcefile As String, destfile As String)
        Try
            File.Copy(sourcefile, destfile, True)
            Return True
        Catch ex As Exception
            LOGGER.Warn(String.Format("Unexpected Error in CopyFile: sourcefile '{0}', destfile '{1}' - ERROR: {2}", sourcefile, destfile, ex.Message))
            UPDATE_ERROR = True
            Return False
        End Try
    End Function
End Class
