Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Grid

Module ModuleHelperMethods

    Public Enum EnumFormatOptions
        [String] = 0
        Currency = 1
        [Decimal] = 2
    End Enum

    Public Enum EnumDateTimePickerDefaultValueOptions
        CurrentDate = 0
        Empty = 1
    End Enum

    Public Function NotNull(Of T)(ByVal value As T, ByVal defaultValue As T) As T
        If IsNothing(value) OrElse String.IsNullOrEmpty(value.ToString) OrElse IsDBNull(value) Then
            Return defaultValue
        Else
            Return value
        End If
    End Function

    Public Function NotNullInt(ByVal value As Integer, ByVal defaultValue As Integer) As Integer
        If IsNothing(value) OrElse IsDBNull(value) OrElse value = 0 Then
            Return defaultValue
        Else
            Return value
        End If
    End Function

    Public Function NotNull(ByVal value As String, ByVal defaultValue As String) As String
        If IsNothing(value) OrElse IsDBNull(value) OrElse String.IsNullOrEmpty(value) Then
            Return defaultValue
        Else
            Return value
        End If
    End Function


    Public Function BoolToInt(bool As Boolean) As Integer
        ' Wandelt einen Boolean Wert in einen Int um
        Return IIf(bool, 1, 0)
    End Function

    Public Function IntToBool(int As Integer) As Boolean
        If int = 0 Then
            Return False
        ElseIf int = 1 Then
            Return True
        Else
            Throw New Exception("IntToBool expects an Integer value that is either 0 or 1")
        End If
    End Function

    Public Function ColorToInt(color As Color) As Integer
        Return System.Drawing.ColorTranslator.ToWin32(color)
    End Function

    Public Function IntToColor(int As Integer) As Color
        Return System.Drawing.ColorTranslator.FromWin32(int)
    End Function

    Public Function StrToBool(str As Object) As Boolean
        Dim result As Boolean = False

        str = TryCast(str, String)

        Try
            result = Convert.ToBoolean(str)
        Catch ex As Exception
            result = False
        End Try

        Return result
    End Function

    Public Function ByteArrayToBitmap(bytearray() As Byte) As Bitmap
        Return New Bitmap(New System.IO.MemoryStream(bytearray))
    End Function

    Public Function StringToByteArray(ByVal hex As String) As Byte()
        Dim NumberChars As Integer = hex.Length

        Dim bytes(NumberChars / 2) As Byte

        For i As Integer = 0 To NumberChars - 1 Step 2
            bytes(i / 2) = Convert.ToByte(hex.Substring(i, 2), 16)
        Next

        Return bytes
    End Function

    Public Function BitmapToByteArray(bitmap As Bitmap) As Byte()
        Dim bytearray As Byte()

        Using stream As New System.IO.MemoryStream
            bitmap.Save(stream, bitmap.RawFormat)
            bytearray = stream.ToArray()
        End Using

        Return bytearray
    End Function

    Public Function IsGroupBox(c As Control)
        Return c.GetType().Name = "GroupBox"
    End Function

    Public Function ParentIsGroupBox(c As Control)
        Return c.Parent.GetType().Name = "GroupBox"
    End Function

    ''' <summary>
    ''' Checks if a property exists on an object
    ''' </summary>
    ''' <param name="obj">The Object to check</param>
    ''' <param name="prop">The Property to check for</param>
    ''' <returns>True, if prop exists</returns>
    Public Function propExists(ByVal obj As Object, ByVal prop As String) As Boolean
        Dim type As Type = obj.GetType
        Return type.GetProperty(prop) IsNot Nothing
    End Function

    Public Function propExistsWithType(ByVal obj As Object, ByVal prop As String, returnType As System.Type)
        Dim type As Type = obj.GetType
        Return type.GetProperty(prop, returnType) IsNot Nothing
    End Function

    ''' <summary>
    ''' Gets a ControlID from Control Name
    ''' </summary>
    ''' <param name="name">Control Name</param>
    ''' <param name="formid">Current Form ID</param>
    ''' <returns>Control ID</returns>
    Public Function GetControlID_for_Name(name As String, formid As Integer) As Integer
        Try
            Dim SQL = "SELECT GUID FROM TBPMO_CONTROL WHERE FORM_ID = " & formid & " and NAME = '" & name & "'"
            Dim ID As Integer = MYDB_ECM.GetScalarValue(SQL)
            If ID > 0 Then
                Return ID
            Else
                Return -1
            End If
        Catch ex As Exception
            MsgBox("Error in GetControlID_for_Name:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Function

    Public Function GetControlID_for_RecordID(name As String, recID As Integer) As Integer
        Try
            Dim SQL = "SELECT CONTROL_ID FROM VWPMO_VALUES WHERE RECORD_ID = " & recID & " and CONTROL_NAME = '" & name & "'"
            Dim ID As Integer = MYDB_ECM.GetScalarValue(SQL)
            If ID > 0 Then
                Return ID
            Else
                LOGGER.Debug("es konnte keine ID für name geholt werden: " & SQL, False)
                Return -1
            End If
        Catch ex As Exception
            MsgBox("Error in GetControlID:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Function

    ''' <summary>
    ''' Gets a Control Name from ControlID
    ''' </summary>
    ''' <param name="Id">ControlID</param>
    ''' <param name="formid">Current Form ID</param>
    ''' <returns>Control Name</returns>
    Public Function Get_Name_for_ControlID(Id As Integer, formid As Integer) As String
        Try
            Dim SQL = "SELECT NAME FROM TBPMO_CONTROL WHERE FORM_ID = " & formid & " AND GUID = " & Id
            Dim Name = MYDB_ECM.GetScalarValue(SQL)

            Return Name
        Catch ex As Exception
            MsgBox("Error in GetName_for_ControlID:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Public Sub OpenFormCalendar()
        Dim frm As New frmCalendar
        frm = frmCalendar.Instance()
        If My.Settings.User_Calendar_isChild = True Then
            frm.MdiParent = MAIN_FORM
        End If


        frm.Show()
    End Sub
    Public Sub OpenViewsUser()
        Dim frm As New frmViewsUser
        frm = frmViewsUser
        frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub
    Public Sub OpenSearchAllOVer()
        Dim frm As New frmGlobalSearch
        frm = frmGlobalSearch
        frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub
    Public Sub OpenStatisticsADDI()
        Dim frm As New frmStatistiscsADDI
        frm = frmStatistiscsADDI
        frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub
    Public Sub Close_Maximized_Forms()
        For i = System.Windows.Forms.Application.OpenForms.Count - 1 To 1 Step -1
            Dim form As Form = System.Windows.Forms.Application.OpenForms(i)
            form.WindowState = FormWindowState.Normal
        Next i
    End Sub
    Public Sub OpenFormOverview()
        Close_Maximized_Forms()
        Dim frm As New frmEntities
        frm = frmEntities.Instance()
        frm.MdiParent = MAIN_FORM

        frm.Show()
    End Sub
    Public Sub OpenFormLevelDesigner()
        For i = System.Windows.Forms.Application.OpenForms.Count - 1 To 1 Step -1
            Dim form As Form = System.Windows.Forms.Application.OpenForms(i)
            form.WindowState = FormWindowState.Normal
        Next i

        Dim frm As New frmLevel_Designer
        frm = frmLevel_Designer.Instance
        frm.MdiParent = MAIN_FORM
        frm.Show()


        'Dim frm2 As New frmTool_ControlDesigner
        'frm2 = frmTool_ControlDesigner.Instance
        'If My.Settings.User_DesignPanels_areChild = True Then
        '    frm2.MdiParent = MAIN_FORM
        'End If

        'frm2.Show()

        'Dim frm3 As New frmTool_ControlProperties
        'frm3 = frmTool_ControlProperties.Instance
        'If My.Settings.User_DesignPanels_areChild = True Then
        '    frm3.MdiParent = MAIN_FORM
        'End If

        'frm3.Show()

    End Sub

    Public Sub OpenRecordView(recordId)
        Try
            JUMP_RECORD_ID = recordId

            Dim frm As New frmRecordView()
            'frm.MdiParent = MAIN_FORM
            frm.Show()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Public Sub OpenFormConstructor(id As Integer, NodeNav As Boolean, EntityID As Int16, Optional recordId As Integer = -1)
        Try
            If CURRENT_OPEN_CONSTRUCTOR_FORMS.Contains(id) Then
                Dim frm1 As New frmConstructor_Main
                frm1.Tag = id
                Dim frmCollection = System.Windows.Forms.Application.OpenForms
                For i As Int16 = 0I To frmCollection.Count - 1I
                    If frmCollection.Item(i).Tag = id Then
                        frmCollection.Item(i).Activate()
                        frmCollection.Item(i).BringToFront()
                        If frmCollection.Item(i).WindowState = FormWindowState.Minimized Then
                            frmCollection.Item(i).WindowState = FormWindowState.Normal
                        End If
                        Exit Sub
                    End If
                Next i
                Exit Sub
            End If

            CURRENT_CONSTRUCTOR_ID = id
            CURRENT_OPEN_CONSTRUCTOR_FORMS.Add(id)

            If NodeNav Then
                Dim frmNN As New frmNodeNavigation(EntityID, CURRENT_CONSTRUCTOR_ID)
                frmNN.Tag = id
                If My.Settings.EntFormsChild = True Then
                    Dim activeChild1 As Form = MAIN_FORM.ActiveMdiChild
                    If activeChild1 IsNot Nothing Then
                        activeChild1.WindowState = FormWindowState.Normal
                    End If
                End If


                If recordId <> -1 Then
                    ' Wenn JUMP_RECORD_ID gesetzt wurde, wird zu diesem Record gesprungen
                    JUMP_RECORD_ID = recordId
                End If
                If My.Settings.EntFormsChild = True Then
                    frmNN.MdiParent = MAIN_FORM
                End If

                frmNN.Show()
            Else
                Dim frm As New frmConstructor_Main()
                frm.Tag = id
                If My.Settings.EntFormsChild = True Then
                    Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
                    If activeChild IsNot Nothing Then
                        activeChild.WindowState = FormWindowState.Normal
                    End If
                End If


                If recordId <> -1 Then
                    ' Wenn JUMP_RECORD_ID gesetzt wurde, wird zu diesem Record gesprungen
                    JUMP_RECORD_ID = recordId
                End If
                If My.Settings.EntFormsChild = True Then
                    frm.MdiParent = MAIN_FORM
                End If

                frm.Show()
            End If




        Catch ex As Exception
            LOGGER.Warn("Error in OpenFormConstructor: " & ex.Message)
            MsgBox("Error in OpenFormConstructor: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Public Sub OpenTaskmanagement()
        Dim frm As New frmTask_Management
        frm = frmTask_Management.Instance()
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenDokumentartt()
        Dim frm As New frmWM_DoctypeConfig
        frm = frmWM_DoctypeConfig.Instance()
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenMenuDesigner()
        Dim frm As New frmMenuDesigner
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenUserKonfig()
        Dim frm As New frmUserKonfig
        frm = frmUserKonfig.Instance()
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub

    Public Sub OpenImageManager()
        Dim frm As New frmQuickStart_Images
        'frm = frmImageManager.Instance()
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenObjecttypeConfig()
        Dim frm As New frmWM_ObjecttypeConfig
        frm = frmWM_ObjecttypeConfig.Instance()
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenRightsmanager()
        Try
            Dim ProductionPath As String = System.IO.Path.Combine(MY_ADDON_PATH, "RightManager", "RecordOrganizer_RightManager.exe")
            Dim DevelPath As String = System.IO.Path.Combine(MY_ADDON_PATH, "RecordOrganizer_RightManager\bin\Debug", "RecordOrganizer_RightManager.exe")

            Dim startInfo As New ProcessStartInfo()
            startInfo.Arguments = """" & MyConnectionString & """"

            If System.IO.File.Exists(ProductionPath) Then
                startInfo.FileName = ProductionPath
            Else
                startInfo.FileName = DevelPath
            End If

            Process.Start(startInfo)
        Catch ex As Exception
            MsgBox("Could not find Right manager: " & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Public Sub OpenWindream_Files()
        Dim frm As New frmWM_Import_Doc_Record
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenWiedervorlage()
        Dim frm As New frmFollowUp
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenLogRecord()
        Dim frm As New frmLogRecord
        frm = frmLogRecord.Instance()
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenTemplatemanagement()
        Dim frm As New frmTemplates
        frm.MdiParent = MAIN_FORM

        Dim activeChild As Form = MAIN_FORM.ActiveMdiChild
        If activeChild IsNot Nothing Then
            activeChild.WindowState = FormWindowState.Normal
        End If

        frm.Show()
    End Sub
    Public Sub OpenFormCockpit()
        Close_Maximized_Forms()
        Dim frm As New frmCockpit
        frm = frmCockpit.Instance()
        frm.MdiParent = MAIN_FORM
        frm.Show()
    End Sub

    Public Function ShortGUID() As String
        Return Guid.NewGuid().ToString().GetHashCode().ToString("x")
    End Function

    Public Function Get_Grid_Sql(ConstructorId As Integer, FormId As Integer, ConstructorDetailID As Integer, ByRef GRID_TYPE As frmConstructor_Main.GridType, UserGuid As Integer, QUICK_VIEW_SQL As String,
                                 IS_SINGLE_RECORD As Boolean, FORM_TYPE As Integer, ByRef VIEW_ID As Integer, ByRef GridControlMain As GridControl, ByRef grvwGrid As GridView, Optional ByRef IS_GEOData As Boolean = False, Optional ByRef NODEVAV As Boolean = False)
        Try
            Dim ViewName As String = "VWPMO_ENTITY_TABLE" & FormId.ToString
            CURRENT_VIEWNAME = ViewName
            Dim EntitySQL As String

            If GRID_TYPE = frmConstructor_Main.GridType.Grid Or NODEVAV Then
                LOGGER.Debug("GridType = Grid", False)
                EntitySQL = "SELECT T.* FROM " & ViewName & " T"
                If IS_GEOData = True Then

                    EntitySQL &= " LEFT OUTER JOIN TBPMO_RECORD_GEODATA T1 ON T.[Record-ID] = T1.RECORD_ID"
                    EntitySQL = EntitySQL.Replace("T.*", "T.*, T1.LATITUDE,T1.LONGITUDE,T1.LOCATION")
                End If
            Else 'Tiles und Carousel bekommen Quick View
                EntitySQL = QUICK_VIEW_SQL

                If EntitySQL = String.Empty Then
                    EntitySQL = "SELECT T.* FROM VWPMO_ENTITY_TABLE" & FormId.ToString & " T"
                    If IS_SINGLE_RECORD = True Or FORM_TYPE = 5 Then

                    Else
                        GRID_TYPE = frmConstructor_Main.GridType.Grid
                        GridControlMain.MainView = grvwGrid
                        VIEW_ID = 3
                    End If
                    ' GridControlMain.MainView = grvwGrid
                Else
                    LOGGER.Debug("Quick-View is configured", False)
                End If
            End If


            Try
                Dim sql = String.Format("SELECT COUNT(*) FROM TBPMO_CONSTRUCTOR_USER_SQL WHERE USER_ID = {0} AND CONSTR_DET_ID = {1} AND SQL_COMMAND IS NOT NULL AND SQL_COMMAND <> ''", USER_GUID, ConstructorDetailID)
                Dim exists = MYDB_ECM.GetScalarValue(SQL)
                If exists = 1 Then
                    sql = String.Format("SELECT SQL_COMMAND FROM TBPMO_CONSTRUCTOR_USER_SQL WHERE USER_ID = {0} AND CONSTR_DET_ID = {1}", USER_GUID, ConstructorDetailID)
                    Dim result = MYDB_ECM.GetScalarValue(SQL)
                    If Not IsNothing(result) Then
                        ' result = result.ToUpper.Replace("@RECORDID", RECORD_ID)
                        result = result.ToUpper.Replace("@USER_ID", UserGuid)
                        EntitySQL = EntitySQL & " " & result.ToString
                        CURRENT_ENTITYSQL_WHERE = result
                    Else
                        CURRENT_ENTITYSQL_WHERE = ""
                    End If
                Else
                    CURRENT_ENTITYSQL_WHERE = ""
                End If
            Catch ex As Exception
                LOGGER.Warn("Error in Get Entity SQL for User: " & vbNewLine & ex.Message)
                MsgBox("Error in Get Entity SQL for User: " & vbNewLine & ex.Message)
            End Try

            Return EntitySQL
        Catch ex As Exception
            LOGGER.Warn("Error in Get_Grid_Sql: " & vbNewLine & ex.Message)
            MsgBox("Error in Get_Grid_Sql: " & vbNewLine & ex.Message)
            Return Nothing
        End Try
    End Function
    Public Function Get_Grid_Sql_NODE_NAV(ConstructorId As Integer, FormId As Integer, ConstructorDetailID As Integer, UserGuid As Integer)
        Try
            Dim ViewName As String = "VWPMO_ENTITY_TABLE" & FormId.ToString
            CURRENT_VIEWNAME = ViewName
            Dim EntitySQL As String

            EntitySQL = "SELECT T.* FROM " & ViewName & " T"


            Try
                Dim sql = String.Format("SELECT COUNT(*) FROM TBPMO_CONSTRUCTOR_USER_SQL WHERE USER_ID = {0} AND CONSTR_DET_ID = {1} AND SQL_COMMAND IS NOT NULL AND SQL_COMMAND <> ''", USER_GUID, ConstructorDetailID)
                Dim exists = MYDB_ECM.GetScalarValue(SQL)
                If exists = 1 Then
                    sql = String.Format("SELECT SQL_COMMAND FROM TBPMO_CONSTRUCTOR_USER_SQL WHERE USER_ID = {0} AND CONSTR_DET_ID = {1}", USER_GUID, ConstructorDetailID)
                    Dim result = MYDB_ECM.GetScalarValue(SQL)
                    If Not IsNothing(result) Then
                        ' result = result.ToUpper.Replace("@RECORDID", RECORD_ID)
                        result = result.ToUpper.Replace("@USER_ID", UserGuid)
                        EntitySQL = EntitySQL & " " & result.ToString
                        CURRENT_ENTITYSQL_WHERE = result
                    Else
                        CURRENT_ENTITYSQL_WHERE = ""
                    End If
                Else
                    CURRENT_ENTITYSQL_WHERE = ""
                End If
            Catch ex As Exception
                LOGGER.Warn("Error in Get Entity SQL for User: " & vbNewLine & ex.Message)
                MsgBox("Error in Get Entity SQL for User: " & vbNewLine & ex.Message)
            End Try

            Return EntitySQL
        Catch ex As Exception
            LOGGER.Warn("Error in Get_Grid_Sql: " & vbNewLine & ex.Message)
            MsgBox("Error in Get_Grid_Sql: " & vbNewLine & ex.Message)
            Return Nothing
        End Try
    End Function

    Public Class SW
        Public label As String
        Public stopwatch As Stopwatch

        Public Sub New(label As String)
            Me.label = label
            stopwatch = New Stopwatch()
            stopwatch.Start()
        End Sub

        Public Function Done() As Long
            If DEBUG = True Then Return 0
            stopwatch.Stop()
            Dim ts As TimeSpan = stopwatch.Elapsed

            Dim timespan_ = String.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
            If ts.Minutes > 0 Then
                timespan_ = String.Format("{0:00}:{1:00}.{2:00}", ts.Minutes, ts.Seconds, ts.Milliseconds / 10)
            ElseIf ts.Seconds > 0 And (ts.Minutes > 0) = False Then
                timespan_ = String.Format("{0:00}.{1:00} seconds", ts.Seconds, ts.Milliseconds / 10)
            ElseIf (ts.Seconds > 0) = False And ts.Milliseconds > 0 Then
                timespan_ = String.Format("{0:00}.{1:00} seconds", ts.Seconds, ts.Milliseconds / 10)
            End If
            If timespan_ <> "00:00.00" Then
                Dim message = String.Format("{0} || {1}", timespan_, label)
                Console.WriteLine(message)
                LOGGER.Debug(message, False)
            End If
            Return stopwatch.ElapsedMilliseconds
        End Function


    End Class

    Public Class PerfomanceHelper
        <Runtime.InteropServices.DllImport("user32.dll")> _
        Public Shared Function SendMessage(hWnd As IntPtr, msg As Int32, wParam As Boolean, lParam As Int32) As Integer
        End Function
        Private Const WM_SETREDRAW As Int32 = &HB

        ''' <summary>
        ''' Verhindert Draw-Events. Am Ende sollte ResumeDraw `aufgerufen` werden.
        ''' </summary>
        ''' <param name="c"></param>
        ''' <remarks></remarks>
        Public Shared Sub SuspendDraw(c As Control)
            SendMessage(c.Handle, WM_SETREDRAW, False, 0)
        End Sub

        ''' <summary>
        ''' Lässt die Draw-Events wieder zu. Davor sollte `SuspendDraw` aufgerufen werden
        ''' </summary>
        ''' <param name="c"></param>
        ''' <remarks></remarks>
        Public Shared Sub ResumeDraw(c As Control)
            SendMessage(c.Handle, WM_SETREDRAW, True, 0)
            c.Refresh()
        End Sub
    End Class

End Module
