Imports DevExpress.XtraNavBar
Imports DevExpress.XtraBars.Ribbon
Imports DevExpress.XtraBars
Imports System.ComponentModel

Public Class frmMain

    'Ausgelagert in ModuleMySettings.vb
    'Dim sql_User_Login As String = "UPDATE TBDD_USER SET LOGGED_IN = @LogInOut, LOGGED_WHERE = '@ANGEMELDETWO' WHERE (LOWER(USERNAME) = LOWER('@user'))"
    'Dim sql_UserID As String = "SELECT GUID FROM TBDD_USER WHERE (LOWER(USERNAME) = LOWER('@user'))"
    'Private USER_GUID


    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            ' Referenz zu frmMain speichern
            MAIN_FORM = Me

            ' Form Titel setzen
            ClassWindowLocation.LoadFormLocationSize(Me, 1, CURRENT_SCREEN_ID, "frmMain")
            Me.Text = Application.ProductName
            LabelVersion.Caption = String.Format("Version {0}", My.Application.Info.Version.ToString)
            LabelUser.Caption = Environment.UserName
            LabelMachine.Caption = My.Computer.Name

            Load_Connection_Dep_Data()

            'Wenn Argumente übergeben wurden, wird Formular geladen und zu record gesprungen
            ClassJumpRecord.ParseArgs()

        Catch ex As Exception
            MsgBox("Error in Load Form:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Connection_Dep_Data()
        SetBackground()

        Dim splash As New frmSplash()
        splash.ShowDialog()

        If USER_IS_ADMIN = True Then
            pageAdmin.Visible = True
        End If

        LabelLoggedIn.Caption = "Anzahl Angemeldete User: " & USERS_LOGGED_IN.ToString()

        'LoadMenuItems()
        LoadMenuItems2()
        LoadQuickStartItems()
        VWPMO_WF_USER_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
        VWPMO_WF_USER_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
        Try
            Dim sql1 As String = String.Format("select * from TBPMO_FILES_USER where HANDLE_TYPE = 'SCAN' and WORKED = 0 AND UPPER(USER_WORK) = '{0}'", Environment.UserName)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql1, "Load ScanFiles")
            If Not IsNothing(DT) Then
                If DT.Rows.Count > 0 Then
                    frmScanFiles.Show()
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Load InBox Scan:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Try
            Dim sql = "UPDATE TBDD_USER SET LOGGED_IN = @LogInOut, LOGGED_WHERE = '@ANGEMELDETWO' WHERE (LOWER(USERNAME) = LOWER('@user'))"
            sql = sql.Replace("@LogInOut", 0)
            sql = sql.Replace("@ANGEMELDETWO", "''")
            sql = sql.Replace("@user", Environment.UserName)
            ClassDatabase.Execute_non_Query(sql)
            sql = "DELETE FROM TBDD_USER_MODULE_LOG_IN WHERE USER_ID = " & USER_GUID & " AND MODULE = 'RECORD_ORGANIZER'"
            ClassDatabase.Execute_non_Query(sql)
            ClassWindowLocation.SaveFormLocationSize(Me, 1, CURRENT_SCREEN_ID, "frmMain")
            ToolStripManager.SaveSettings(Me)

            My.Settings.Save()

        Catch ex As Exception

        End Try
        'TempDateien löschen
        Try
            For Each _file In TEMP_FILES
                System.IO.File.Delete(_file)
            Next
        Catch ex As Exception

        End Try
    End Sub

    Private Shared Function LoadNoImage() As Bitmap
        Return Nothing
    End Function

    Private Shared Function LoadImage(path As Object)
        If Not IsDBNull(path) Then
            Dim filepath As String = DirectCast(path, String)
            filepath = CType(path, String)
            If System.IO.File.Exists(path) Then
                Return New Bitmap(filepath)
            Else
                Return LoadNoImage()
            End If
        Else
            Return LoadNoImage()
        End If
    End Function

    Public Sub LoadMenuItems2()
        Dim SQL As String = "SELECT * FROM TBPMO_MENU_FORM"
        Dim dtRootMenu As DataTable = ClassDatabase.Return_Datatable(SQL)

        pageForms.Groups.Clear()

        If dtRootMenu.Rows.Count <> 0 Then

            For Each row As DataRow In dtRootMenu.Rows

                Dim MenuID As Integer = row.Item("GUID")
                Dim groupTitle As String = row.Item("MENU_ENTRY")
                Dim group As New RibbonPageGroup(groupTitle)
                Dim dtSubMenu As DataTable
                Dim image As Bitmap = LoadImage(row.Item("ICON_PATH"))

                group.Glyph = image
                group.AllowTextClipping = False

                SQL = "SELECT * FROM TBPMO_MENU_FORM_ENTRIES WHERE MENU_FORM_ID = " & MenuID
                dtSubMenu = ClassDatabase.Return_Datatable(SQL)

                If dtSubMenu.Rows.Count <> 0 Then

                    For Each subRow As DataRow In dtSubMenu.Rows

                        Dim itemTitle As String = subRow.Item("MENU_ENTRY")
                        Dim tag As String = subRow.Item("FORM_ID")
                        Dim item As New BarButtonItem(ribbonMain.Manager, itemTitle)

                        Dim subimage As Bitmap = LoadImage(subRow.Item("ICON_PATH"))

                        item.RibbonStyle = RibbonItemStyles.SmallWithText
                        item.Tag = tag
                        item.Glyph = subimage

                        AddHandler item.ItemClick, AddressOf BarButtonItemClick

                        group.ItemLinks.Add(item)

                    Next

                    pageForms.Groups.Add(group)
                End If

            Next

        End If
    End Sub

    Public Sub LoadQuickStartItems()
        Dim SQL2 As String = "SELECT * FROM TBPMO_FORM_CONSTRUCTOR ORDER BY SEQUENCE_MENU"
        Dim dt As DataTable = ClassDatabase.Return_Datatable(SQL2)
        Dim image2 As Bitmap = LoadNoImage()

        'Do While 0 < groupQuickAccess.ItemLinks.Count
        '    groupQuickAccess.ItemLinks.Remove(groupQuickAccess.ItemLinks(0))
        'Loop

        'If dt.Rows.Count <> 0 Then

        '    For Each row As DataRow In dt.Rows
        '        If Not IsDBNull(row.Item("MENU_IMG")) Then
        '            Dim bimg() As Byte = row.Item("MENU_IMG")
        '            Dim bitmap As Bitmap = ByteArrayToBitmap(bimg)
        '            image2 = bitmap
        '        End If

        '        Dim title As String = row.Item("FORM_TITLE")
        '        Dim index As Integer = row.Item("SEQUENCE_MENU")
        '        Dim tag As Integer = row.Item("GUID")
        '        Dim item As New BarButtonItem(ribbonMain.Manager, title)
        '        item.RibbonStyle = RibbonItemStyles.Large
        '        item.Caption = title
        '        item.Tag = tag
        '        item.Glyph = image2

        '        AddHandler item.ItemClick, AddressOf ToolbarButtonItemClick

        '        groupQuickAccess.ItemLinks.Add(item)

        '    Next

        'End If


        Do While 0 < groupQuickAccess.ItemLinks.Count
            groupQuickAccess.ItemLinks.Remove(groupQuickAccess.ItemLinks(0))
        Loop

        If dt.Rows.Count <> 0 Then

            For Each row As DataRow In dt.Rows
                If Not IsDBNull(row.Item("MENU_IMG")) Then
                    Dim bimg() As Byte = row.Item("MENU_IMG")
                    Dim bitmap As Bitmap = ByteArrayToBitmap(bimg)
                    image2 = bitmap
                End If

                Dim title As String = row.Item("FORM_TITLE")
                Dim index As Integer = row.Item("SEQUENCE_MENU")
                Dim tag As Integer = row.Item("GUID")
                Dim item As New BarButtonItem(ribbonMain.Manager, title)
                item.RibbonStyle = RibbonItemStyles.Large
                item.Caption = title
                item.Tag = tag
                item.Glyph = image2

                AddHandler item.ItemClick, AddressOf ToolbarButtonItemClick
                groupQuickAccess.ItemLinks.Add(item)

            Next

        End If
    End Sub


    Private Sub BarButtonItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs)
        Dim formId As Integer = Integer.Parse(e.Item.Tag)

        Cursor = Cursors.WaitCursor
        OpenFormInputFor(formId, 1)
        Cursor = Cursors.Default
    End Sub

    Private Sub ToolbarButtonItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs)
        Dim formId As Integer = Integer.Parse(e.Item.Tag)

        Cursor = Cursors.WaitCursor
        OpenFormConstructor(formId)
        Cursor = Cursors.Default
    End Sub

    Private Sub NavbarItem_Click(sender As Object, e As NavBarLinkEventArgs)
        Dim formID As Integer = Integer.Parse(e.Link.Item.Tag)

        Cursor = Cursors.WaitCursor
        OpenFormConstructor(formID)
        Cursor = Cursors.Default
    End Sub

    Private Sub MenuItemClick(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim formId As Integer = Integer.Parse(item.Tag)

        Cursor = Cursors.WaitCursor
        OpenFormInputFor(formId, 1)
        Cursor = Cursors.Default
    End Sub
    Private Sub MenuItem2Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim formId As Integer = Integer.Parse(item.Tag)
        Cursor = Cursors.WaitCursor
        OpenFormConstructor(formId)
        Cursor = Cursors.Default
    End Sub

    Private Shared Sub QuickAccessClick(sender As Object, e As EventArgs)
        Dim btn As ToolStripButton = CType(sender, ToolStripButton)
        Dim formId As Integer
        formId = Integer.Parse(sender.tag)
        OpenFormConstructor(formId)
    End Sub

    Private Sub SetBackground()
        Dim ctrl As Control
        Dim ctrlMDI As MdiClient

        For Each ctrl In Me.Controls
            Try
                ctrlMDI = CType(ctrl, MdiClient)
                ctrlMDI.BackColor = Me.BackColor
            Catch ex As Exception

            End Try
        Next
    End Sub

    Delegate Sub SetWindowTitleDelegate(t As String)
    Public Sub SetWindowTitle(t As String)
        If Me.InvokeRequired Then
            Dim d As New SetWindowTitleDelegate(AddressOf SetWindowTitle)
            Me.Invoke(d, New Object() {t})
        Else
            Me.Text = t
        End If
    End Sub

    Delegate Sub SetWindowBackgroundDelegate(i As Bitmap)
    Public Sub SetWindowBackground(i As Bitmap)
        If Me.InvokeRequired Then
            Dim d As New SetWindowBackgroundDelegate(AddressOf SetWindowBackground)
            Me.Invoke(d, New Object() {i})
        Else
            Me.BackgroundImage = i
            Me.BackgroundImageLayout = ImageLayout.Center
        End If
    End Sub
   
    Sub Refresh_TaskReminder()
        Try
            Me.VWPMO_WF_USER_ACTIVETableAdapter.Fill(Me.DD_DMSDataSet.VWPMO_WF_USER_ACTIVE, Environment.UserName)
            If DD_DMSDataSet.VWPMO_WF_USER_ACTIVE.Rows.Count > 0 Then
                NotifyIcon1.Visible = True
                NotifyIcon1.ShowBalloonTip(50000, "Unerledigte Tasks", "Sie haben unerledigte Tasks in Ihrem Verantwortungsbereich." & vbNewLine & "Bitte überprüfen Sie Ihre Workflow-Tasks", ToolTipIcon.Info)
            End If
        Catch ex As Exception
            MsgBox("Error in Refresh_TaskReminder:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub EbenenKonfiguratorToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Cursor = Cursors.WaitCursor
        OpenFormOverview()
        Cursor = Cursors.Default
    End Sub
    Private Sub KalenderToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Cursor = Cursors.WaitCursor
        OpenFormCalendar()
        Cursor = Cursors.Default
    End Sub

    Private Sub BeendenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        Me.Close()
    End Sub

    Private Sub FormateProduktionenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenFormConstructor(1)
    End Sub

    Private Sub WorkflowTaskmanagementToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenTaskmanagement()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Refresh_TaskReminder()
    End Sub

    Private Sub frmMain_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        ' Repaint Form on Resize End
        Me.Invalidate(True)
        Me.Update()
    End Sub

    Private Sub frmMain_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Refresh_TaskReminder()
        Timer1.Start()
        If Sett_ConstructorStart <> 0 Then
            Cursor = Cursors.WaitCursor
            OpenFormConstructor(Sett_ConstructorStart)
            Cursor = Cursors.Default
        End If
        'Lizenz abgellaufen, überprüfen ob User Admin ist
        If LICENSE_COUNT < USERS_LOGGED_IN Then
            If USER_IS_ADMIN = True Then
                ClassLogger.Add(">> User is Admin - Timer will be started", False)
                'If USER_LANGUAGE = "de-DE" Then
                MsgBox("Sie haben nun 3 Minuten Zeit eine neue Lizenz zu vergeben!", MsgBoxStyle.Information)
                'Else
                '    MsgBox("You now got 3 minutes to update the license!", MsgBoxStyle.Information)
                'End If

                'Timer starten
                If TimerClose3Minutes.Enabled = False Then
                    TimerClose3Minutes.Start()
                End If
            End If
        End If
        'If DOCTYPE_COUNT_ACTUAL > LICENSE_DOCTYPE_COUNT Then
        '    If CURRENT_USER_IS_ADMIN = True Then
        '        ClassLogger.Add(">> User is Admin - Timer will be started", False)
        '        If USER_LANGUAGE = "de-DE" Then
        '            MsgBox("Sie haben nun 3 Minuten Zeit eine neue Lizenz zu vergeben!", MsgBoxStyle.Information)
        '        Else
        '            MsgBox("You now got 3 minutes to update the license!", MsgBoxStyle.Information)
        '        End If

        '        'Timer starten
        '        If TimerClose3Minutes.Enabled = False Then
        '            TimerClose3Minutes.Start()
        '        End If
        '    End If
        'End If


    End Sub

    Private Sub Workflow_Taskmanagement_Click(sender As Object, e As EventArgs) Handles NotifyIcon1.Click

    End Sub

    Private Sub DokumentartkonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenDokumentartt()
    End Sub

    Private Sub MenuKonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenMenuDesigner()
    End Sub

    Private Sub UserKonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenUserKonfig()
    End Sub
    Private Sub ImageManagerToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenImageManager()
    End Sub

    Private Sub tsQuickMenue_LocationChanged(sender As Object, e As EventArgs)
        'Console.WriteLine("locChanged" & tsQuickMenue.Location.ToString)
        'If tsQuickMenue.Location.ToString <> "{X=0,Y=0}" Then
        '    SaveMySettingsValue("tsQuickMenueLocation", tsQuickMenue.Location.ToString)
        'End If


    End Sub
    Private Sub GrundeinstellungenWindreamToolStripMenuItem_Click(sender As Object, e As EventArgs)
        OpenObjecttypeConfig()
    End Sub

    Private Sub MenuStrip1_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs)

    End Sub

    Private Sub GrundeinstellungenToolStripMenuItem_Click(sender As Object, e As EventArgs)
        frmConfiguration_Basic.ShowDialog()
    End Sub

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        OpenFormCalendar()
    End Sub

    Private Sub itemInfo_ItemClick(sender As Object, e As ItemClickEventArgs) Handles itemInfo.ItemClick
        frmAbout.ShowDialog()
    End Sub

    Private Sub itemExit_ItemClick(sender As Object, e As ItemClickEventArgs) Handles itemExit.ItemClick
        Me.Close()
    End Sub

    Private Sub itemSettings_ItemClick(sender As Object, e As ItemClickEventArgs) Handles itemSettings.ItemClick
        frmConfig_Basic.ShowDialog()
        If CONNECTION_CHANGED = True Then
            Load_Connection_Dep_Data()
        End If
    End Sub

    Private Sub BarButtonItem3_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        Cursor = Cursors.WaitCursor
        OpenFormOverview()
        Cursor = Cursors.Default
    End Sub

    Private Sub BarButtonItem4_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem4.ItemClick
        OpenTaskmanagement()
    End Sub

    Private Sub BarButtonItem5_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem5.ItemClick
        OpenUserKonfig()
    End Sub

    Private Sub BarButtonItem6_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem6.ItemClick
        OpenMenuDesigner()
    End Sub

    Private Sub BarButtonItem7_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem7.ItemClick
        OpenImageManager()
    End Sub

    Private Sub BarButtonItem8_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem8.ItemClick
        Close_Maximized_Forms()
        OpenDokumentartt()
    End Sub

    Private Sub BarButtonItem9_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem9.ItemClick
        Close_Maximized_Forms()
        OpenObjecttypeConfig()
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        frmConfiguration_Basic.ShowDialog()
    End Sub

    Private Sub BarButtonItem10_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem10.ItemClick
        frmConfig_Basic.ShowDialog()
    End Sub

    Private Sub BarButtonItem12_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem12.ItemClick
        OpenWiedervorlage()
    End Sub

    Private Sub BarButtonItem13_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem13.ItemClick
        OpenLogRecord()
    End Sub

    Private Sub BarButtonItem14_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem14.ItemClick
        Dim frm As New frmConnections
        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub BarButtonItem16_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem16.ItemClick
        Close_Maximized_Forms()
        Dim frm As New frmConstructorDesigner
        frm.MdiParent = Me
        frm.Show()
    End Sub

    Private Sub BarButtonItem17_ItemClick(sender As Object, e As ItemClickEventArgs) Handles BarButtonItem17.ItemClick
        OpenTemplatemanagement()
    End Sub

    Private Sub TimerClose3Minutes_Tick(sender As Object, e As EventArgs) Handles TimerClose3Minutes.Tick
        If LICENSE_EXPIRED = True Or LICENSE_COUNT < USERS_LOGGED_IN Then
            'If USER_LANGUAGE = "de-DE" Then
            '    MsgBox("Global Indexer wird nun geschlossen, weil keine neue Lizenzdaten eingegeben wurden!", MsgBoxStyle.Information)
            'Else
            MsgBox("Global Indexer will now be closed, cause no new license was updated!", MsgBoxStyle.Information)
            'End If
            Me.Close()
        Else
            TimerClose3Minutes.Stop()
        End If
    End Sub

    Private Sub frmMain_KeyUp(sender As Object, e As KeyEventArgs) Handles MyBase.KeyUp
        Select Case e.KeyCode
            Case Keys.F12
                Try
                    frmLicense.ShowDialog()
                Catch ex As Exception

                End Try
        End Select
    End Sub
End Class
