Imports System.IO
Imports System.Globalization
Imports System.ComponentModel

Public Class ClassHelper
    Private Shared BW_DocPath As String
    Private Shared BW_DocID As Integer
    Public Shared Function FORMAT_WM_PATH(WMpath As String)
        Try
            Dim ochanged As Boolean = False
            If WMpath.StartsWith("W:") Then
                WMpath = WMpath.Replace("W:", WMPATH_PREFIX)
                ochanged = True
            ElseIf WMpath.StartsWith("\") Then
                If WMpath.StartsWith(WMPATH_PREFIX) = False Then
                    WMpath = WMPATH_PREFIX & WMpath
                    ochanged = True
                End If
            End If
            LOGGER.Debug("WMpath is: " & WMpath)
            Return WMpath
        Catch ex As Exception
            Return WMpath
        End Try

    End Function
    Public Shared Function GetRelPath(WMpath As String)
        Try
            If WMpath.StartsWith("W:") Then
                WMpath = WMpath.Replace("W:", "")

            ElseIf WMpath.StartsWith("\") Then
                If WMpath.StartsWith(WMPATH_PREFIX) = False Then
                    WMpath = WMpath.Replace("WMPATH_PREFIX:", "")
                End If
            End If
            LOGGER.Debug("WMpath is: " & WMpath)
            Return WMpath
        Catch ex As Exception
            Return WMpath
        End Try

    End Function
    Public Shared Function Format_Currency(value As String, language As String)
        Try
            If IsNothing(value) Then
                Return ""
            End If

            If language <> "de-DE" Then
                value = value.Replace(",", ".")
            End If

            Dim dValue = Double.Parse(value)

            Dim ci = Threading.Thread.CurrentThread.CurrentCulture
            Dim nfi As NumberFormatInfo = ci.NumberFormat.Clone()
            nfi.CurrencySymbol = "" ' KEIN Currency Symbol

            Return dValue.ToString("C", nfi)
        Catch ex As Exception
            Return value.ToString()
        End Try
    End Function

    Public Shared Function Convert_Date(input As String, format As String)
        Try
            Dim dt As Date = CDate(input)
            Dim result = dt.ToString(format, CultureInfo.InvariantCulture)
            Return result
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error while converting value '" & input & "' to date....." & ex.Message)
            Return input
        End Try

    End Function
    Public Shared Function CheckDBNull(input As Object, back_Value As String)
        If IsDBNull(input) Then
            If back_Value = "String" Then
                Return ""
            Else
                Return True
            End If
        Else
            If back_Value = "String" Then
                Return input.ToString
            Else
                Return False
            End If
        End If
    End Function
    Public Shared Function Convert_to_Database_Date(input As String)
        Try
            Dim dt As Date = CDate(input)
            Dim result = dt.ToString("yyyy-MM-dd", Nothing)
            Return result
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error while converting value '" & input & "' to date(Convert_to_Database_Date)....." & ex.Message)
            Return input
        End Try

    End Function
    Public Shared Function Get_TempFilename()
        'Eine tempfile generieren
        Dim tempFilename = My.Computer.FileSystem.GetTempFileName()
        'Nur den Filenamen ohne Erweiterung
        Dim tempName = Path.GetDirectoryName(tempFilename) & "\" & Path.GetFileNameWithoutExtension(tempFilename)
        'tempfile lsöchen
        If My.Computer.FileSystem.FileExists(tempFilename) Then
            My.Computer.FileSystem.DeleteFile(tempFilename)
        End If
        Return tempName
    End Function
    Public Shared Function CheckFileIsInUse(ByVal filename) As Boolean
        Dim fs As Integer = FreeFile()
        Dim inuse As Boolean = False
        If File.Exists(filename) Then
            Try
                Using f As New IO.FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
                    ' thisFileInUse = False
                End Using
            Catch
                inuse = True
            End Try

            Try
                FileOpen(fs, filename, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
            Catch ex As Exception
                LOGGER.Warn("File " & filename & " inuse or not able to open - message: " & ex.Message)
                inuse = True
            Finally
                FileClose(fs)
            End Try
        End If
        Return inuse
    End Function
    Public Shared Function Versionierung_Datei(Dateiname As String)
        Dim extension
        Dim _NewFileString
        Try
            Dim version As Integer = 1

            Dim Stammname As String = Path.GetDirectoryName(Dateiname) & "\" & Path.GetFileNameWithoutExtension(Dateiname)
            extension = Path.GetExtension(Dateiname)

            Dim _neuername As String = Stammname
            'Dim MoveFilename As String = DATEINAME.Replace(element.Value, "")
            'Überprüfen ob File existiert
            If File.Exists(_neuername & extension) = False Then
                _NewFileString = _neuername
            Else
                Do While File.Exists(_neuername & extension)
                    version = version + 1
                    _neuername = Stammname & "~" & version
                    _NewFileString = _neuername
                Loop
            End If
            Return _NewFileString & extension
        Catch ex As Exception
            LOGGER.Warn(" - Error in versioning file - error: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in versioning file:")
            Return ""
        End Try
    End Function
    Public Shared Function CleanFilename(ByVal sFilename As String,
      Optional ByVal REPLACEChar As String = "") As String

        ' alle nicht zulässigen Zeichen ersetzen
        Return System.Text.RegularExpressions.Regex.Replace(
          sFilename, "[?*^""<>|]", REPLACEChar)
    End Function
    Public Shared Function File_open(RESULT_DOC_PATH As Object, DocID As String)
        Try
            RESULT_DOC_PATH = FORMAT_WM_PATH(RESULT_DOC_PATH)
            CURRENT_OFFICE_FILE_CHANGED = False
            If RESULT_DOC_PATH <> Nothing Then
                If USER_GENERAL_VIEWER = "NONE" Then
                    Dim EXT = Path.GetExtension(RESULT_DOC_PATH)
                    EXT = EXT.Replace(".", "")
                    Dim sql = String.Format("SELECT VIEWER FROM TBPMO_DOC_USER_VIEW WHERE USER_ID = {0} AND FILE_EXTENSION = '{1}'", USER_GUID, EXT)
                    Dim DT As DataTable = MYDB_ECM.GetDatatable(sql)
                    If DT.Rows.Count = 1 Then
                        Select Case DT.Rows(0).Item("VIEWER")
                            Case "DOC_VIEW"
                                OPEN_DOCVIEW(RESULT_DOC_PATH, DocID)
                        End Select
                    Else
                        File_SYSOPEN(RESULT_DOC_PATH, DocID)
                    End If
                Else
                    Select Case USER_GENERAL_VIEWER
                        Case "DOC-VIEW"
                            OPEN_DOCVIEW(RESULT_DOC_PATH, DocID)
                    End Select
                End If
                Return True
            Else
                MSGBOX_Handler("ERROR", "", "Sorry, but the docpath for doc-id: " & DocID & " is nothing!")
                Return False
                LOGGER.Debug("RESULT_DOC_PATH IS NOTHING")
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in File_open:" & vbNewLine & ex.Message & vbNewLine & RESULT_DOC_PATH & vbNewLine & "DocID: " & DocID, MsgBoxStyle.Critical)
            LOGGER.Warn("Error in File_open: " & ex.Message & vbNewLine & " - Path: " & RESULT_DOC_PATH & " - DocID: " & DocID)
            Return False
        End Try
    End Function
    Public Shared Sub Open_Folder(RESULT_DOC_PATH As Object, DocID As String)
        Try
            If RESULT_DOC_PATH <> Nothing Then
                RESULT_DOC_PATH = FORMAT_WM_PATH(RESULT_DOC_PATH)
                Dim _path = Path.GetDirectoryName(RESULT_DOC_PATH)
                FOLDER_OPEN(_path, DocID)
            Else
                LOGGER.Debug("RESULT_DOC_PATH IS NOTHING")
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Open_Folder:" & vbNewLine & ex.Message & vbNewLine & RESULT_DOC_PATH & vbNewLine & "DocID: " & DocID, MsgBoxStyle.Critical)
            LOGGER.Warn("Error in Open_Folder: " & ex.Message & vbNewLine & " - Path: " & RESULT_DOC_PATH & " - DocID: " & DocID)
        End Try
    End Sub
    Public Shared Sub OPEN_DOCVIEW(Doc_Path As String, DocID As Integer)
        Try
            Dim DocView
            DocView = Nothing
            DocView = CreateObject("WMPViewXNG.Viewer")
            ' open the viewer
            Dim viewer_string = Doc_Path.Substring(2)
            DocView.ViewFile(viewer_string)
            CURRENT_DOCVIEW_PATH = viewer_string
            CURRENT_DOCVIEW = DocView
        Catch ex As Exception
            MsgBox("Unexpected Error in DocView Open:" & vbNewLine & ex.Message & vbNewLine & Doc_Path & vbNewLine & "DocID: " & DocID, MsgBoxStyle.Critical)
            LOGGER.Warn("Error in DocView Open: " & ex.Message & vbNewLine & " - Path: " & Doc_Path & " - DocID: " & DocID)
            File_SYSOPEN(Doc_Path, DocID)
        End Try
    End Sub
    Private Shared Sub File_SYSOPEN(RESULT_DOC_PATH As Object, DocID As String)
        Try
            If RESULT_DOC_PATH <> Nothing Then

                BW_DocPath = RESULT_DOC_PATH
                BW_DocID = DocID

                Dim BWFileHandler As New BackgroundWorker
                AddHandler BWFileHandler.DoWork, AddressOf BWFileHandler_DoWork
                BWFileHandler.RunWorkerAsync()

            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in File_SYSOPEN:" & vbNewLine & ex.Message & vbNewLine & RESULT_DOC_PATH & vbNewLine & "DocID: " & DocID, MsgBoxStyle.Critical)
            LOGGER.Warn("Error in File_SYSOPEN: " & ex.Message & vbNewLine & " - Path: " & RESULT_DOC_PATH & " - DocID: " & DocID)
        End Try

    End Sub
    Private Shared Sub BWFileHandler_DoWork()
        Try

            Dim oMyProcess = New Process()
            Dim oExtension
            Dim oSql
            Try
                'Dim oPSI As New ProcessStartInfo(BW_DocPath)
                oMyProcess.StartInfo.FileName = BW_DocPath
                oMyProcess.StartInfo.UseShellExecute = True
                oMyProcess.StartInfo.RedirectStandardOutput = False
                oMyProcess.Start()
                Dim ProcID = oMyProcess.GetCurrentProcess.Id
                oExtension = Path.GetExtension(BW_DocPath).ToLower
                LOGGER.Debug($"Checking oExtension [{oExtension}]...")
                If FILE_FORMATS_CHANGE_DURING_EDIT.Contains(oExtension) Then
                    oSql = $"SELECT dwVersionID FROM VWPMO_DOC_SEARCH WHERE DocID = {BW_DocID}"
                    Dim odwVersionId = MYDB_ECM.GetScalarValue(oSql)

                    Dim oInsert = $"INSERT INTO TBPMO_DOC_ID_CHANGED (USER_ID,PROCESS_ID,VERSION_ID,OLD_DOC_ID,DOC_PATH) VALUES ({USER_GUID},'{ProcID.ToString}',{odwVersionId},{BW_DocID},'{BW_DocPath}')"
                    MYDB_ECM.ExecuteNonQuery(oInsert)
                End If

                'oMyProcess.WaitForExit()
            Catch ex As Exception
                LOGGER.Warn("Error in Process1.Start(): " & ex.Message & vbNewLine & " - Path: " & BW_DocPath & " - DocID: " & BW_DocID)
                Exit Sub
            End Try

        Catch ex As Exception
            LOGGER.Warn("Error in Process.Start(): " & ex.Message & vbNewLine & " - Path: " & BW_DocPath & " - DocID: " & BW_DocID)
            Try
                Process.Start(BW_DocPath)
            Catch ex1 As Exception
                LOGGER.Warn("Error in Process.Start(1): " & ex1.Message & vbNewLine & " - Path: " & BW_DocPath & " - DocID: " & BW_DocID)
            End Try
        End Try
    End Sub
    Private Shared Sub FOLDER_OPEN(PATH As Object, DocID As String)
        Try
            If PATH <> Nothing Then
                LOGGER.Debug("in FOLDER_OPEN(" & PATH & ")")
                If System.IO.Directory.Exists(PATH) = True Then
                    Process.Start(PATH)
                Else
                    MsgBox("Folder '" & PATH & "' not existing or accessible!", MsgBoxStyle.Exclamation)
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in FOLDER_OPEN:" & vbNewLine & ex.Message & vbNewLine & PATH & vbNewLine & "DocID: " & DocID, MsgBoxStyle.Critical)
            LOGGER.Warn("Error in FOLDER_OPEN: " & ex.Message & vbNewLine & " - Path: " & PATH & " - DocID: " & DocID)
        End Try

    End Sub
    Shared Function Convert_Date_2_Form_Format(p1 As Date) As Date
        Throw New NotImplementedException
    End Function
    Public Shared Function InsertEssential_Log(REFERENCE_KEY As Integer, REFERENCE_STRING As String, COMMENT As String)
        Try
            COMMENT = COMMENT.Replace("'", "")
            Dim insert = String.Format("INSERT INTO TBPMO_LOG_ESSENTIALS (REFERENCE_KEY,REFERENCE_STRING,COMMENT,ADDED_WHO) VALUES ({0},'{1}','{2}','{3}')", REFERENCE_KEY, REFERENCE_STRING, COMMENT, USER_USERNAME)

            Dim result = MYDB_ECM.ExecuteNonQuery(insert)
            Return result
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in InsertEssential_Log: " & ex.Message)
            Return False
        End Try
    End Function
    Public Shared Function DeleteRecord(SELECTED_RECORD_ID As Integer, Optional Comment As String = "")
        Try
            Dim DeleteRecordSQL = String.Format("EXEC [dbo].[PRPMO_DELETE_RECORD] {0}, '{1}','{2}'", SELECTED_RECORD_ID, USER_USERNAME, Comment)
            Dim result As Boolean = MYDB_ECM.ExecuteNonQuery(DeleteRecordSQL)
            If result = False Then
                Dim msg = "Der Datensatz '" & SELECTED_RECORD_ID & "' konnte nicht gelöscht werden. Überprüfen Sie das log"
                If USER_LANGUAGE <> "de-DE" Then
                    msg = "The record '" & SELECTED_RECORD_ID & "' could not be deleted. Check the log"
                End If
                MsgBox(msg, MsgBoxStyle.Exclamation)
            Else
                ClassProxy.PRPROXY_RECORD_DEL(SELECTED_RECORD_ID, CURRENT_ENTITY_ID)
            End If
            LOGGER.Info($"Deleted Record [{SELECTED_RECORD_ID}] Result was [{result}]: ")
            Return result
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in DeleteRecord: " & ex.Message)
            Return False
        End Try
    End Function
    Public Shared Sub MSGBOX_Handler(type As String, Caption As String, info1 As String, Optional info2 As String = "")
        Dim msg = info1
        If info2 <> "" Then
            msg &= vbNewLine & vbNewLine & info2
        End If
        If type = "ERROR" Then
            MessageBox.Show(msg, Caption, MessageBoxButtons.OK, MessageBoxIcon.Error)
            LOGGER.Warn(msg)
        ElseIf type = "INFO" Then
            MessageBox.Show(msg, Caption, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End If
    End Sub
    Public Shared Function Check_Record_Read_only(RECORD_ID As Integer, ENTITY_ID As Integer)
        Dim sql = ""
        Try
            sql = SQL_RECORD_AND_FILE_READ_ONLY
            sql = sql.Replace("@RECORDID", RECORD_ID)
            sql = sql.Replace("@RECORD_ID", RECORD_ID)
            sql = sql.Replace("@USER_ID", USER_GUID)
            sql = sql.Replace("@USER_GUID", USER_GUID)
            sql = sql.Replace("@ENTITY_ID", ENTITY_ID)
            sql = sql.Replace("@USERNAME", USER_USERNAME)
            sql = sql.Replace("@USER_NAME", USER_USERNAME)
            LOGGER.Debug("RIGHT_ONLY_READ_RECORD_DOC SQL: (When true then disable) '" & sql & "'")
            Return CBool(MYDB_ECM.GetScalarValue(sql))
        Catch ex As Exception
            LOGGER.Warn("SQL_RIGHT_READ_AND_VIEW_ONLY: " & sql)
            Return False
        End Try
    End Function
    Public Shared Function Check_File_Read_only(RECORD_ID As Integer, ENTITY_ID As Integer)
        Dim sql = ""
        Try

            sql = SQL_DOC_READ_ONLY
            sql = sql.Replace("@RECORDID", RECORD_ID)
            sql = sql.Replace("@RECORD_ID", RECORD_ID)
            sql = sql.Replace("@USER_ID", USER_GUID)
            sql = sql.Replace("@USER_GUID", USER_GUID)
            sql = sql.Replace("@ENTITY_ID", ENTITY_ID)
            sql = sql.Replace("@USERNAME", USER_USERNAME)
            sql = sql.Replace("@USER_NAME", USER_USERNAME)
            LOGGER.Debug("RIGHT_ONLY_READ_COC SQL: (When true then disable) '" & sql & "'")
            Return CBool(MYDB_ECM.GetScalarValue(sql))
        Catch ex As Exception
            LOGGER.Warn("RIGHT_WINDREAM_FORBIDDEN: " & sql)
            Return False
        End Try
    End Function
    Public Shared Sub Create_USER_FILE_TABLE()
        Try
            Dim sql = String.Format("SELECT *, CONVERT(BIT,0) AS DELETE_FILE FROM TBPMO_FILES_USER WHERE (UPPER(USER_WORK) = UPPER('{0}')) AND WORKED = 0", USER_USERNAME)
            CURRENT_TBPMO_FILES_USER = MYDB_ECM.GetDatatable(sql)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Unexpected error while creating User_File_Table")
        End Try
    End Sub
    Public Shared Function DELETE_PMO_FILE_USER(GUID As Integer)
        Try
            Dim del As String = String.Format("DELETE FROM TBPMO_FILES_USER WHERE GUID = {0}", GUID)
            Return MYDB_ECM.ExecuteNonQuery(del)
        Catch ex As Exception
            MsgBox("Unexpected Error in DELETE_PMO_FILE_USER: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Public Shared Function DecryptString(ciphertext As String, MethodName As String)
        Dim result As String
        Dim wrapper As New ClassEncryption("!35452didalog=")
        ' DecryptData throws if the wrong password is used.
        Try
            result = wrapper.DecryptData(ciphertext)
            Return result
        Catch ex As Exception
            LOGGER.Warn("The ciphertext for Method'" & MethodName & "' could not be decrypted")
            Return ""
        End Try
    End Function
    Public Shared Function FILTER_DATATABLE(BaseDatatable As DataTable, expression As String, sortstring As String)
        Try
            'Schema übernehmen
            Dim filteredData As DataTable = BaseDatatable.Clone()
            'Einfügevariante
            BaseDatatable.Select(expression, sortstring).CopyToDataTable(filteredData, LoadOption.PreserveChanges)
            Console.WriteLine("Found {0} rows.", filteredData.Rows.Count)
            'Dim filteredData = BaseDatatable.Select(expression).CopyToDataTable()
            Return filteredData
        Catch ex As Exception
            LOGGER.Warn("unexpected error in FILTER_DATATABLE: " & ex.Message)
            Return Nothing
        End Try

    End Function
    Public Shared Function GetDocrecordLinks(pRECORDID As Integer)
        Try
            Dim oSQL = $"SELECT * FROM TBPMO_DOC_RECORD_LINK WHERE RECORD_ID = {pRECORDID}"
            CURRENT_DT_TBPMO_DOC_RECORD_LINK = MYDB_ECM.GetDatatable(oSQL)
        Catch ex As Exception
            LOGGER.Warn("Unexpected Error in GetDocrecordLinks: " & ex.Message)
            Return False
        End Try
    End Function
End Class
