Imports System.IO
Imports System.Globalization
Imports DD_LIB_Standards
Public Class ClassHelper
    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
            ClassLogger.Add("Unexpected Error while converting value '" & input & "' to date....." & ex.Message, False)
            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
            ClassLogger.Add("Unexpected Error while converting value '" & input & "' to date(Convert_to_Database_Date)....." & ex.Message, False)
            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
                ClassLogger.Add("File " & filename & " inuse or not able to open - message: " & ex.Message, True)
                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
            ClassLogger.Add(" - Error in versioning file - error: " & vbNewLine & ex.Message)
            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error in versioning file:")
            Return ""
        End Try
    End Function
    '' <summary>
    ''' Ersetzt alle nicht zulässigen Zeichen im angegebenen Dateinamen
    ''' </summary>
    ''' <param name="sFilename">Dateiname ohne Pfadangabe</param>
    ''' <param name="sChar">Ersatzzeichen für alle unzulässigen Zeichen 
    ''' im Dateinamen</param>
    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 Sub File_open(RESULT_DOC_PATH As Object, DocID As String)
        Try
            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 UPPER(FILE_EXTENSION) = UPPER('{1}')", USER_GUID, EXT)
                    Dim DT As DataTable = ClassDatabase.Return_Datatable(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
            Else
                MSGBOX_Handler("ERROR", "", "Sorry, but the docpath for doc-id: " & DocID & " is nothing!")
                If LogErrorsOnly = False Then ClassLogger.Add(" >> 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)
            ClassLogger.Add("Error in File_open: " & ex.Message & vbNewLine & " - Path: " & RESULT_DOC_PATH & " - DocID: " & DocID, True)
        End Try
    End Sub
    Public Shared Sub Open_Folder(RESULT_DOC_PATH As Object, DocID As String)
        Try
            If RESULT_DOC_PATH <> Nothing Then
                Dim _path = Path.GetDirectoryName(RESULT_DOC_PATH)
                FOLDER_OPEN(_path, DocID)
            Else
                If LogErrorsOnly = False Then ClassLogger.Add(" >> 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)
            ClassLogger.Add("Error in Open_Folder: " & ex.Message & vbNewLine & " - Path: " & RESULT_DOC_PATH & " - DocID: " & DocID, True)
        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)
            ClassLogger.Add("Error in DocView Open: " & ex.Message & vbNewLine & " - Path: " & Doc_Path & " - DocID: " & DocID, True)
            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
                If System.IO.File.Exists(RESULT_DOC_PATH) = True Then
                    Process.Start(RESULT_DOC_PATH)
                Else
                    If clsWD_GET.WDFile_exists(RESULT_DOC_PATH, True) = False Then
                        MSGBOX_Handler("ERROR", "", "File '" & RESULT_DOC_PATH & "' not existing!")
                    Else
                        MSGBOX_Handler("ERROR", "", "File '" & RESULT_DOC_PATH & "' is existing but You are not provided with reading rights! Please inform Your admin!")
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in File_SYSOPEN:" & vbNewLine & ex.Message & vbNewLine & RESULT_DOC_PATH & vbNewLine & "DocID: " & DocID, MsgBoxStyle.Critical)
            ClassLogger.Add("Error in File_SYSOPEN: " & ex.Message & vbNewLine & " - Path: " & RESULT_DOC_PATH & " - DocID: " & DocID, True)
        End Try

    End Sub
    Private Shared Sub FOLDER_OPEN(PATH As Object, DocID As String)
        Try
            If PATH <> Nothing Then

                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)
            ClassLogger.Add("Error in FOLDER_OPEN: " & ex.Message & vbNewLine & " - Path: " & PATH & " - DocID: " & DocID, True)
        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 = clsDatabase.Execute_non_Query(insert, False)
            Return result
        Catch ex As Exception
            ClassLogger.Add("Unexpected Error in InsertEssential_Log: " & ex.Message, True, False)
            Return False
        End Try
    End Function
    Public Shared Function DeleteRecord(ByVal SELECTED_RECORD_ID)
        Try
            Dim DeleteRecordSQL = String.Format("EXEC [dbo].[PRPMO_DELETE_RECORD] {0}, '{1}'", SELECTED_RECORD_ID, USER_USERNAME)
            Dim result As Boolean = ClassDatabase.Execute_non_Query_withConn(DeleteRecordSQL, 1)
            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

            Return result
        Catch ex As Exception
            ClassLogger.Add("Unexpected Error in DeleteRecord: " & ex.Message, True)
            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)
            ClassLogger.Add(msg, True)
        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)
            If LogErrorsOnly = False Then ClassLogger.Add(" >> RIGHT_ONLY_READ_RECORD_DOC SQL: (When true then disable) '" & sql & "'", False)
            Return CBool(ClassDatabase.Execute_Scalar(sql, True))
        Catch ex As Exception
            ClassLogger.Add(">> 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)
            If LogErrorsOnly = False Then ClassLogger.Add(" >> RIGHT_ONLY_READ_COC SQL: (When true then disable) '" & sql & "'", False)
            Return CBool(ClassDatabase.Execute_Scalar(sql, True))
        Catch ex As Exception
            ClassLogger.Add(">> 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 = ClassDatabase.Return_Datatable(sql, True)
        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 ClassDatabase.Execute_non_Query(del, True)
        Catch ex As Exception
            MsgBox("Unexpected Error in DELETE_PMO_FILE_USER: " & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
End Class
