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 = ClassDatabase.Execute_Scalar(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 = ClassDatabase.Execute_Scalar(SQL, True)
            If ID > 0 Then
                Return ID
            Else
                If LogErrorsOnly = False Then ClassLogger.Add(" >> 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 = ClassDatabase.Execute_Scalar(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, Optional recordId As Integer = -1)
        Try
            CURRENT_CONSTRUCTOR_ID = id
            Dim frm As New frmConstructor_Main()
            ' frm = frmForm_Constructor.Instance()

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

            If recordId <> -1 Then
                ' Wenn JUMP_RECORD_ID gesetzt wurde, wird zu diesem Record gesprungen
                JUMP_RECORD_ID = recordId
            End If

            frm.MdiParent = MAIN_FORM
            frm.Show()
        Catch ex As Exception
            ClassLogger.Add("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 frmWD_Dokumentart_Konfig
        frm = frmWD_Dokumentart_Konfig.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 frmWD_ObjecttypeConfig
        frm = frmWD_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()
        'Dim path As String = ClassDatabase.Execute_Scalar("SELECT PATH_ADDONS FROm TBPMO_KONFIGURATION WHERE GUID = 1")
        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 frmWD_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)
        Try
            Dim ViewName As String = "VWTEMP_PMO_FORM" & FormId.ToString
            Dim EntitySQL As String

            If GRID_TYPE = frmConstructor_Main.GridType.Grid Then
                If LogErrorsOnly = False Then ClassLogger.Add(" >> 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 VWTEMP_PMO_FORM" & 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
                    If LogErrorsOnly = False Then ClassLogger.Add(" >> 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 = ClassDatabase.Execute_Scalar(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 = ClassDatabase.Execute_Scalar(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
                ClassLogger.Add("Error in Get Entity SQL for User: " & vbNewLine & ex.Message, True)
                MsgBox("Error in Get Entity SQL for User: " & vbNewLine & ex.Message)
            End Try

            Return EntitySQL
        Catch ex As Exception
            ClassLogger.Add("Error in Get_Grid_Sql: " & vbNewLine & ex.Message, True)
            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
            stopwatch.Stop()
            Dim message = String.Format("{0, 5}ms || {1}", stopwatch.ElapsedMilliseconds, label)
            Console.WriteLine(message)
            If LogErrorsOnly = False Then ClassLogger.Add(message, False)
            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
