Imports DevExpress.XtraScheduler
Imports System.IO
Imports WINDREAMLib

Public Class frmFormInput



#Region "+++++ Konstanten +++++"
    'Private akt_ctrl As Control
    Private thisformid As Integer = Nothing
    Private SelectedRecordID As Integer = 0
    Private SelectedFormID As Integer = Nothing
    Private m_Moving As Boolean = False
    Private insert = False
    Private DocView As Boolean = False
    Private _windream As New ClassWindream
    'Private Shared _Instance As frmFormInput = Nothing
    'Public Shared Function Instance() As frmFormInput
    '    If _Instance Is Nothing OrElse _Instance.IsDisposed = True Then
    '        _Instance = New frmFormInput
    '    End If
    '    _Instance.BringToFront()
    '    Return _Instance
    'End Function

#End Region


    Public Sub SetFormTitles(title As String)
        Me.Text = title
        '   BindingNavigatorCountItem.Text = BindingNavigatorCountItem.Text.Replace("Datensätzen", title)
    End Sub

#Region "+++++ Form Events +++++"
    Public Sub LoadOverview_Grid()
        Try
            'Load Input Grid
            Dim _sqlGrid As String = "SELECT SQL_COMMAND FROM TBPMO_FORM_SQL WHERE FORM_ID = " & thisformid
            Dim _sql = ClassDatabase.Execute_Scalar(_sqlGrid)
            If (Not IsDBNull(_sql)) Then
                Dim dt As DataTable = ClassDatabase.Return_Datatable(_sql)
                If dt Is Nothing = False Then
                    'BindingSource for Navigator
                    Me.BindingSourceDGV.DataSource = dt
                    'bind Datatable to bindingsource
                    Me.dgvInput.DataSource = Me.BindingSourceDGV
                    'Me.dgvOverview.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
                End If
            Else
                MsgBox("No entries for actual Form. Pleas insert the first values.", MsgBoxStyle.Exclamation)
            End If


        Catch ex As Exception
            MsgBox("Error in Load Overview Grid:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub frmLevel_Designer_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            Me.VWPMO_CONTROL_SCREENTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_RECORDTableAdapter.Connection.ConnectionString = MyConnectionString

            thisformid = CURRENT_FORM_ID
            Me.VWPMO_CONTROL_SCREENTableAdapter.Fill(Me.DD_DMSDataSet.VWPMO_CONTROL_SCREEN, thisformid)

            CtrlBuilder = New ClassControlBuilder(pnlView)
            CtrlCommandUI = New ClassControlCommandsUI(CtrlBuilder,
                                                       ContextMenuStrip1,
                                                       AddressOf NewEditAppointment,
                                                       AddressOf OpenFormData)
            If ClassDatabase.Init = True Then
                LoadOverview_Grid()
                LoadFormProperties()
                CtrlCommandUI.LoadControls(CURRENT_FORM_ID)
                ' FocusedRow_Change ruft bereits LoadControlValues auf
                FocusedRow_Change()
            End If

            ClassWindowLocation.LoadFormLocationSize(Me, thisformid, CURRENT_SCREEN_ID)

        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub HandleToolTip(sender As Object, e As EventArgs)
        Console.WriteLine("show tooltip")
    End Sub
#End Region

#Region "+++++ Layout +++++"
    Private Sub frmFormInput_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        LoadLayout()
    End Sub

    Private Sub frmLevel_Designer_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Try
            SaveLayout()
            ClassWindowLocation.SaveFormLocationSize(Me, thisformid, CURRENT_SCREEN_ID)
            My.Settings.Save()

            'frmForm_Overview.Instance.Show()
            'frmTool_ControlProperties.Instance.Close()
            'frmTool_ControlDesigner.Instance.Close()
        Catch ex As Exception

        End Try
    End Sub

    Public Sub LoadLayout()

        Try
            'DataGridView Layout laden
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), "SCREEN" & CURRENT_SCREEN_ID & "-FORM" & thisformid & "-UserLayout.xml")
            dgvInput.MainView.RestoreLayoutFromXml(XMLPath)


            'Splitter Layout laden
            Dim LayoutPath = Path.Combine(Application.UserAppDataPath(), "SCREEN" & CURRENT_SCREEN_ID & "-FORM" & thisformid & "-SplitterLayout.xml")

            Dim layout As ClassLayout = New ClassLayout(LayoutPath)
            Dim settings As System.Collections.Generic.List(Of ClassSetting)
            settings = layout.Load()

            If settings.Count = 0 Then
                settings.Add(New ClassSetting("SplitContainerMain", SplitContainerMain.SplitterDistance))
                settings.Add(New ClassSetting("SplitContainerDetails", SplitContainerDetails.SplitterDistance))
                layout.Save(settings)
            End If

            For Each s As ClassSetting In settings
                Select Case s._name
                    Case "SplitContainerMain"
                        SplitContainerMain.SplitterDistance = Integer.Parse(s._value)
                    Case "SplitContainerDetails"
                        SplitContainerDetails.SplitterDistance = Integer.Parse(s._value)
                End Select
            Next
        Catch notFoundEx As System.IO.FileNotFoundException
            ClassLogger.Add("Layout added for Screen " & CURRENT_SCREEN_ID & ", Form " & thisformid)
        Catch ex As Exception
            MsgBox("Error while loading Layout!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub


    Public Sub SaveLayout()
        Try
            'DataGridView Layout speichern
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), "SCREEN" & CURRENT_SCREEN_ID & "-FORM" & thisformid & "-UserLayout.xml")
            dgvInput.MainView.SaveLayoutToXml(XMLPath)

            'Splitter Layout speichern
            Dim LayoutPath = Path.Combine(Application.UserAppDataPath(), "SCREEN" & CURRENT_SCREEN_ID & "-FORM" & thisformid & "-SplitterLayout.xml")

            Dim layout As ClassLayout = New ClassLayout(LayoutPath)
            Dim settings As System.Collections.Generic.List(Of ClassSetting) = New System.Collections.Generic.List(Of ClassSetting)
            settings.Add(New ClassSetting("SplitContainerMain", SplitContainerMain.SplitterDistance))
            settings.Add(New ClassSetting("SplitContainerDetails", SplitContainerDetails.SplitterDistance))
            layout.Save(settings)
        Catch ex As Exception
            MsgBox("Error while saving Layout!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub


#End Region

#Region "+++++ Load Funktionen +++++"
    Public Sub LoadFormProperties()
        'Dim NAME_SQL As String = "SELECT NAME FROM TBPMO_FORM WHERE GUID = " & CURRENT_FORM_ID
        Dim TITLE_SQL As String = "SELECT FORM_TITLE FROM TBPMO_FORM_VIEW WHERE FORM_ID = " & thisformid
        'Dim name = ClassDatabase.Execute_Scalar(NAME_SQL)
        Dim title = ClassDatabase.Execute_Scalar(TITLE_SQL)

        DocView = ClassDatabase.Execute_Scalar("SELECT DOCUMENT_VIEW FROM TBPMO_FORM_VIEW WHERE FORM_ID = " & thisformid)
        If DocView = True Then
            If _windream.Init = True Then
                Me.SplitContainerDetails.Panel2Collapsed = False
            End If

        Else
            Me.SplitContainerDetails.Panel2Collapsed = True
        End If
        'SetFormName(name)
        SetFormTitles(title)
    End Sub

    Private Sub Load_Value(recID As Integer, CONTROLID As Integer, control As Control)
        Try
            Dim sq = "SELECT * FROM VWPMO_VALUES WHERE RECORD_ID = " & recID & " and CONTROL_ID = " & CONTROLID
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sq)
            Dim result = DT.Rows(0).Item("VALUE")
            Select Case DT.Rows(0).Item("CONTROL_TYPE_ID")
                Case 2 ' TextBox
                    Dim textbox As TextBox = DirectCast(control, TextBox)
                    textbox.Text = result
                Case 10 ' CheckBox
                    Dim checkbox As CheckBox = DirectCast(control, CheckBox)
                    checkbox.Checked = CBool(result)
                Case 3 ' ComboBox
                    Dim combobox As ComboBox = DirectCast(control, ComboBox)
                    combobox.SelectedIndex = combobox.FindStringExact(result)
                Case 4 'DateTimePicker
                    Dim datepicker As DevExpress.XtraEditors.DateEdit = DirectCast(control, DevExpress.XtraEditors.DateEdit)
                    datepicker.DateTime = Date.Parse(result)
                Case Else
                    ' MsgBox(DT.Rows(0).Item("CONTROL_TYPE_ID"))
            End Select
        Catch ex As Exception
            MsgBox("Error in Load_Value:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Function Return_SearchPAttern(ByVal content As String)
        Select Case content
            Case "Form-ID (Entity)"
                Return thisformid
            Case "Record-ID"
                Return SelectedRecordID

        End Select
    End Function
    Private Sub load_Documents()
        Try
            If DocView Then
                Dim SQL = "SELECT WINDREAM_SEARCH,SEARCH_PATTERN1,SEARCH_PATTERN2,SEARCH_PATTERN3,SEARCH_PATTERN4,SEARCH_PATTERN5 FROM TBPMO_FORM_VIEW WHERE FORM_ID = " & thisformid & " and SCREEN_ID = " & CURRENT_SCREEN_ID
                Dim DT As DataTable = ClassDatabase.Return_Datatable(SQL)
                If DT.Rows.Count = 1 Then
                    If Not IsDBNull(DT.Rows(0).Item(0)) Then
                        Dim WD_Suche = DT.Rows(0).Item(0)
                        Dim SP1 = DT.Rows(0).Item(1)
                        Dim SP2 = DT.Rows(0).Item(2)
                        Dim SP3 = DT.Rows(0).Item(3)
                        Dim SP4 = DT.Rows(0).Item(4)
                        Dim SP5 = DT.Rows(0).Item(5)


                        'Eine tempfile generieren
                        Dim tempFilename1 = My.Computer.FileSystem.GetTempFileName()
                        'Nur den Filenamen ohne Erweiterung
                        Dim tempName = Path.GetFileNameWithoutExtension(tempFilename1)
                        'tempfile lsöchen
                        If My.Computer.FileSystem.FileExists(tempFilename1) Then
                            My.Computer.FileSystem.DeleteFile(tempFilename1)
                        End If
                        Try
                            Dim temppath = Path.GetTempPath

                            Dim fileContents As String
                            fileContents = My.Computer.FileSystem.ReadAllText(WD_Suche)
                            fileContents.Replace("Í", "Ö")
                            If SP1.ToString <> String.Empty Then
                                SP1 = Return_SearchPAttern(SP1.ToString)
                                fileContents = fileContents.Replace("%pattern1%", SP1)
                                fileContents = fileContents.Replace("471101", SP1)
                            End If
                            If SP2.ToString <> String.Empty Then
                                SP2 = Return_SearchPAttern(SP2.ToString)
                                fileContents = fileContents.Replace("%pattern2%", SP2)
                                fileContents = fileContents.Replace("471101", SP2)
                            End If
                            If SP3.ToString <> String.Empty Then
                                SP3 = Return_SearchPAttern(SP3.ToString)
                                fileContents = fileContents.Replace("%pattern3%", SP3)
                                fileContents = fileContents.Replace("471102", SP3)
                            End If
                            If SP4.ToString <> String.Empty Then
                                SP4 = Return_SearchPAttern(SP4.ToString)
                                fileContents = fileContents.Replace("%pattern4%", SP4)
                                fileContents = fileContents.Replace("471103", SP4)
                            End If
                            If SP5.ToString <> String.Empty Then
                                SP5 = Return_SearchPAttern(SP5.ToString)
                                fileContents = fileContents.Replace("%pattern5%", SP5)
                                fileContents = fileContents.Replace("471105", SP5)
                            End If





                            'Die windream File zusammensetzen
                            Dim newfilename = temppath & tempName & ".wdf"
                            My.Computer.FileSystem.WriteAllText(newfilename, fileContents, False)
                            ' XML-Datei initialisieren
                            Dim xml As New System.Xml.XmlDocument()
                            ' XML-Datei öffnen und laden
                            xml.Load(newfilename)
                            xml.Save(newfilename)
                            TEMP_FILES.Add(newfilename)
                            Dim windreamSucheErgebnisse As WMObjects = Me._windream.GetSearchDocuments(newfilename)
                            If Not IsNothing(windreamSucheErgebnisse) AndAlso windreamSucheErgebnisse.Count > 0 Then
                                AxObjectListControl.SetIconMode(True)
                                AxObjectListControl.RemoveAllColumnHeader()

                                Me.tslblAnzahl_Dokumente.Text = windreamSucheErgebnisse.Count & " gefundene Dateien"
                                Dim param As New List(Of String)
                                'The file name
                                param.Add("szLongName")
                                'The size
                                param.Add("dwCreationDate")
                                param.Add("dwCreation_Time")

                                Me.AxObjectListControl.SetSession(_windream.oSession, "foo", "bar")
                                'Change the satus icon
                                'ICON STATES:
                                Me.AxObjectListControl.SetStatusIcon(0)

                                'Change the icon
                                Me.AxObjectListControl.SetStatusIcon(2)
                                'Add all search params
                                For Each spar As String In param
                                    'You need to use the column name here
                                    'Please note that some attributes or indices will not be displayed
                                    'Try not to add the same header twice, it will throw cause problems if you do that
                                    Me.AxObjectListControl.AddColumnHeader(spar, 200)
                                Next
                                'Execute the search
                                Dim results As WMObjects = windreamSucheErgebnisse
                                'Set the contents without displaying them
                                AxObjectListControl.SetContentsEx(results)
                                'Change the icon
                                AxObjectListControl.SetStatusIcon(5)
                                'Display the results...
                                'The Previous Object Count
                                Dim poc As Integer = 0
                                'Display new objects, as long as the objectcount changes after displaying the objects

                                Do Until (poc <> AxObjectListControl.GetObjectCount)
                                    poc = AxObjectListControl.GetObjectCount
                                    'If you want, you can display more items at a time
                                    'But do not display to many at a time or the user interface could freeze
                                    'Maybe try 50
                                    AxObjectListControl.DisplayResults(5)

                                Loop
                                AxObjectListControl.SetStatusIcon(3)


                            End If
                            If My.Computer.FileSystem.FileExists(newfilename) Then
                                My.Computer.FileSystem.DeleteFile(newfilename)
                            End If

                        Catch ex As Exception
                            MsgBox("Error in execute-windreamSearch:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                        End Try

                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in load_Documents:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try


    End Sub

#End Region

#Region "+++++ Mouse/Key Events +++++"
    Private Sub Control_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown

    End Sub
    Private Sub Control_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp

    End Sub
    Private Sub Control_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

    End Sub


#End Region

    Sub OpenFormData(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim ctrl As Control = sender
        Cursor = Cursors.WaitCursor
        ClassFunctionCommandsUI.OpenFormData(ctrl.Name, thisformid)
        Cursor = Cursors.Default
    End Sub

    Sub NewEditAppointment(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Dim ctrl As Control = sender
        ClassFunctionCommandsUI.NewEditAppointment(ctrl.Name, thisformid, SelectedRecordID, pnlView.Controls)
    End Sub

    Private Sub FocusedRow_Change()
        Try
            If gvMainView.Columns.Count = 0 Then
                Exit Sub
            End If
            Dim RecordID
            If gvMainView.RowCount > 0 Then
                RecordID = gvMainView.GetFocusedRowCellValue(gvMainView.Columns(0).FieldName)
                If RecordID Is Nothing Then
                    Exit Sub
                End If
            End If

            Dim CONTROL_ID As Integer
            If RecordID Is Nothing = False Then
                If (Not IsDBNull(RecordID)) Then
                    ' TODO: AUCH IN CONTSTRUCTOR
                    ' TODO: Doppelte einträge bei INSERT und UPDATE fixen
                    ' TODO: FormID wird falsch oder nicht gesetzt
                    SelectedRecordID = RecordID
                    ' SelectedFormID = RowView.Item(1)
                    RefreshRecordByID(SelectedRecordID)

                    ClassControlValues.LoadControlValuesList(thisformid, pnlView.Controls)
                    ClassControlValues.LoadControlValuesListWithPlaceholders(thisformid, SelectedRecordID, CURRENT_PARENT_ID, pnlView.Controls)
                    ClassControlValues.LoadControlValues(SelectedRecordID, CURRENT_PARENT_ID, thisformid, pnlView.Controls)
                End If
                load_Documents()
            End If

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

    Private Sub ToolStrip_Notice(text As String)
        If text.Length > 0 Then
            tsstat_lbl.Text = text
            tsstat_lbl.Visible = True
        Else
            tsstat_lbl.Visible = False
        End If
    End Sub
    Private Sub RefreshRecordByID(RECORD_ID As Integer)
        Try
            Me.TBPMO_RECORDTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_RECORD, CType(RECORD_ID, Integer))
        Catch ex As System.Exception
            System.Windows.Forms.MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub BindingNavigatorDeleteItem_Click(sender As Object, e As EventArgs)
        Dim result As MsgBoxResult
        result = MessageBox.Show("Möchten Sie den Datensatz wirklich löschen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            Dim sql As String = "DELETE FROM TBPMO_CONTROL_VALUE WHERE RECORD_ID = " & SelectedRecordID
            If ClassDatabase.Execute_non_Query(sql) = True Then ' Delete der Controls erfolgreich ausgeführt, jetzt der Record
                sql = "DELETE FROM TBPMO_RECORD WHERE GUID = " & SelectedRecordID
                If ClassDatabase.Execute_non_Query(sql) = True Then
                    LoadOverview_Grid()
                    ToolStrip_Notice("Der Datensatz wurde erfolgreich gelöscht - " & Now)
                End If
            End If

        End If
    End Sub

    Private Sub tsbtnrefresh_Click(sender As Object, e As EventArgs) Handles tsbtnrefresh.Click
        LoadOverview_Grid()
    End Sub

    Private Sub tsButtonAdd_Click(sender As Object, e As EventArgs) Handles tsButtonAdd.Click
        'CtrlCommandUI.LoadControls(thisformid)
        ClassControlValues.ClearControlValues(pnlView.Controls)
        ClassControlValues.UnloadControlValuesList(SelectedRecordID, thisformid, pnlView.Controls)
        ClassControlValues.LoadControlValuesList(thisformid, pnlView.Controls)
        ClassControlValues.LoadDefaultValues(thisformid, SelectedRecordID, pnlView.Controls)

        'Das Flag INSERT nach LoadControls setzen
        CtrlCommandUI.IsInsert = True
    End Sub

    Private Sub tsButtonSave_Click(sender As Object, e As EventArgs) Handles tsButtonSave.Click
        SelectedRecordID = 0
        If gvMainView.Columns.Count > 0 Then
            Dim RecordID = gvMainView.GetFocusedRowCellValue(gvMainView.Columns("Record-ID").FieldName)
            If RecordID Is Nothing And gvMainView.RowCount > 0 Then
                Exit Sub
            Else
                If Not RecordID = Nothing Then
                    SelectedRecordID = RecordID
                End If
            End If
        End If


        Dim ResultMessage = CtrlCommandUI.SaveRecord(SelectedRecordID, thisformid)

        LoadOverview_Grid()
        If SelectedRecordID > 0 Then
            Refresh_CreatedChangedRecordByID(SelectedRecordID)

        End If


        'Refresh_CreatedChangedRecordByID(thisrecordID)
        ToolStrip_Notice(ResultMessage)
        'tsstatus_Detail_show(True, ResultMessage)
    End Sub

    Private Sub tsButtonDelete_Click(sender As Object, e As EventArgs) Handles tsButtonDelete.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Möchten Sie den Datensatz wirklich löschen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            If CtrlCommandUI.DeleteRecord(SelectedRecordID) = True Then
                LoadOverview_Grid()
                ToolStrip_Notice("Der Datensatz wurde erfolgreich gelöscht - " & Now)
            End If
        End If
    End Sub

    Sub tserstellt_Detail_show(vis As Boolean, txt As String)
        Me.tserstellt_Detail.Text = txt
        tserstellt_Detail.Visible = vis
    End Sub

    Public Sub Refresh_CreatedChangedRecordByID(RECORD_ID As Integer)
        Try
            Dim result = ClassDatabase.Execute_Scalar("select 'Added by ' + ADDED_WHO + ' when ' + CONVERT(VARCHAR(16),ADDED_WHEN,20) + ', Changed by ' + COALESCE(CHANGED_WHO,'') + ' when ' + COALESCE(CONVERT(VARCHAR(16),CHANGED_WHEN,20),'') FROM TBPMO_RECORD WHERE GUID = " & RECORD_ID)
            If IsDBNull(result) Or IsNothing(result) Then
                'Me.tserstellt_Details.Text = ""
                tserstellt_Detail_show(False, "")
            Else
                'Me.tserstellt_Details.Text = result.ToString
                tserstellt_Detail_show(True, result.ToString)
            End If

        Catch ex As System.Exception
            MsgBox("Error in Refresh_CreatedChangedRecordByID:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub gvMainView_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gvMainView.FocusedRowChanged
        FocusedRow_Change()
    End Sub

    Private Sub StammdatenEditierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles StammdatenEditierenToolStripMenuItem.Click
        Dim MenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim ContextMenu As ContextMenuStrip = MenuItem.Owner
        Dim SourceControl As Control = ContextMenu.SourceControl
        Dim MasterDataId As Integer = DirectCast(SourceControl.Tag, ClassControlMetadata).Id

        frmQuickInput.ShowDialog()
    End Sub

    Private Sub LäscheAlleFilterEtcToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LäscheAlleFilterEtcToolStripMenuItem.Click
        gvMainView.ClearColumnsFilter()
        gvMainView.ClearGrouping()
        gvMainView.ClearSelection()
    End Sub

    Private Sub dgvInput_Click(sender As Object, e As EventArgs) Handles dgvInput.Click

    End Sub
End Class

