Imports System.IO
Imports System.Text
Imports DD_LIB_Standards
Public Class frmDocRecordLink

    Public Property Documents As New List(Of ClassWindreamDocGrid.WindreamDoc)

    Private CURRENT_LINK_ENTITY_ID As Integer = 0
    Private ENTITY_LOAD_ACTIVE As Boolean = False

    Private Class ClassEntity
        Public title As String
        Public id As Integer

        Public Overrides Function ToString() As String
            Return Me.title
        End Function
    End Class
    Private Function GET_CURRENT_ENTITY_DATA()
        Dim oDatatable As DataTable = CURRENT_DT_ENTITY_RECORDS.Copy
        Return oDatatable
    End Function
    Sub Refresh_Grid_Data(current As Boolean, ENTITY_DATATABLE As DataTable)
        Dim DT_RECORDS As DataTable
        If current = True Then
            DT_RECORDS = GET_CURRENT_ENTITY_DATA()
        Else
            DT_RECORDS = ENTITY_DATATABLE
        End If


        Try
            DT_RECORDS.Columns.Add("already linked", Type.GetType("System.Boolean")).SetOrdinal(0)
            DT_RECORDS.Columns("already linked").DefaultValue = False
        Catch ex As Exception

        End Try

        Try
            For Each row As DataRow In CURRENT_DT_SELECTED_FILES.Rows
                Dim DOC_ID = row.Item("DOC_ID")
                Dim sel = String.Format("select T.RECORD_ID FROM TBPMO_DOC_RECORD_LINK T, TBPMO_RECORD T1 WHERE T.RECORD_ID = T1.GUID AND T1.FORM_ID = {0} AND T.DOC_ID = {1}", CURRENT_LINK_ENTITY_ID, DOC_ID)
                Dim DTRECS_LINKED As DataTable = MYDB_ECM.GetDatatable(sel)
                For Each recrow As DataRow In DTRECS_LINKED.Rows
                    For Each rowrecsdisplay As DataRow In DT_RECORDS.Rows
                        If rowrecsdisplay.Item("Record-ID") = recrow.Item("RECORD_ID") Then
                            rowrecsdisplay.Item("already linked") = True
                        Else
                            rowrecsdisplay.Item("already linked") = False
                        End If
                    Next
                Next
            Next
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error in displaying already linked", ex.Message, ex.StackTrace)
        End Try
        grvwGrid.Columns.Clear()
        dgEntityRecords.DataSource = DT_RECORDS
        grvwGrid.Columns.Item("already linked").Fixed = True
        grvwGrid.PopulateColumns()
        dgEntityRecords.RefreshDataSource()
        grvwGrid.OptionsView.ColumnAutoWidth = False
        grvwGrid.BestFitColumns()
    End Sub
    Private Sub frmDocRecordLink_Load(sender As Object, e As EventArgs) Handles Me.Load
        ' OLD WAY
        If Documents.Count = 0 Then
            ENTITY_LOAD_ACTIVE = True
            If ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count = 1 Then
                txtFileInfo.Text = ClassWindreamDocGrid.DT_RESULTFILES.Rows(0).Item("DOC_PATH")
            Else
                txtFileInfo.Text = String.Format("{0} files selected for linking to record", ClassWindreamDocGrid.DT_RESULTFILES.Rows.Count)
            End If
            Try
                If IsNothing(CURRENT_DT_ENTITY_RECORDS) Then
                    Me.Close()
                End If
                If CURRENT_LINK_ENTITY_ID = 0 Then
                    Refresh_Grid_Data(True, Nothing)
                    CURRENT_LINK_ENTITY_ID = CURRENT_ENTITY_ID
                Else
                    Dim DT_RESULT As DataTable
                    If CURRENT_LINK_ENTITY_ID = CURRENT_ENTITY_ID Then
                        DT_RESULT = CURRENT_DT_ENTITY_RECORDS
                    Else
                        DT_RESULT = ReturnDataforEntity(CURRENT_LINK_ENTITY_ID)
                    End If

                    If Not IsNothing(DT_RESULT) Then
                        Refresh_Grid_Data(False, DT_RESULT)
                    End If
                End If


                Dim DT_ENTITIES As DataTable = GetENTITIES()
                Dim oSelectedIndex As Integer = 0

                If DT_ENTITIES.Rows.Count = 0 Then
                    Exit Sub
                End If
                Dim oCount = 0
                For Each row As DataRow In DT_ENTITIES.Rows
                    Dim entity As New ClassEntity
                    entity.title = row.Item("FORM_TITLE")
                    entity.id = row.Item("FORM_ID")
                    cmbConstructorForms.Items.Add(entity)
                    If CURRENT_LINK_ENTITY_ID = entity.id Then
                        txtcurrSichtData.Text = entity.title
                        oSelectedIndex = oCount
                    End If
                    oCount += 1
                Next
                If USER_LANGUAGE = "de-DE" Then
                    Me.Text = CURRENT_DT_SELECTED_FILES.Rows.Count.ToString & " Datei(en) mit Datensatz verknüpfen:"
                Else
                    Me.Text = "Link " & CURRENT_DT_SELECTED_FILES.Rows.Count.ToString & " files with record:"
                End If
                ' Den index der aktuell geöffneten ConstructorForm setzen
                cmbConstructorForms.SelectedIndex = oSelectedIndex

            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error in frmDocRecordLink_Load", ex.Message, ex.StackTrace)
            End Try

            Load_DocGrid_Layout()
            bsiInfo.Caption = "Waiting for record-Selection....."


        End If

        If Documents.Count > 0 Then
            ENTITY_LOAD_ACTIVE = True
            If Documents.Count = 1 Then
                txtFileInfo.Text = Documents.First.DocPath
            Else
                txtFileInfo.Text = String.Format("{0} files selected for linking to record", Documents.Count)
            End If
            Try
                If IsNothing(CURRENT_DT_ENTITY_RECORDS) Then
                    Me.Close()
                End If
                If CURRENT_LINK_ENTITY_ID = 0 Then
                    Refresh_Grid_Data(True, Nothing)
                    CURRENT_LINK_ENTITY_ID = CURRENT_ENTITY_ID
                Else
                    Dim DT_RESULT As DataTable
                    If CURRENT_LINK_ENTITY_ID = CURRENT_ENTITY_ID Then
                        DT_RESULT = CURRENT_DT_ENTITY_RECORDS
                    Else
                        DT_RESULT = ReturnDataforEntity(CURRENT_LINK_ENTITY_ID)
                    End If

                    If Not IsNothing(DT_RESULT) Then
                        Refresh_Grid_Data(False, DT_RESULT)
                    End If
                End If


                Dim DT_ENTITIES As DataTable = GetENTITIES()
                Dim oSelectedIndex As Integer = 0

                If DT_ENTITIES.Rows.Count = 0 Then
                    Exit Sub
                End If
                Dim oCount = 0
                For Each row As DataRow In DT_ENTITIES.Rows
                    Dim entity As New ClassEntity
                    entity.title = row.Item("FORM_TITLE")
                    entity.id = row.Item("FORM_ID")
                    cmbConstructorForms.Items.Add(entity)
                    If CURRENT_LINK_ENTITY_ID = entity.id Then
                        txtcurrSichtData.Text = entity.title
                        oSelectedIndex = oCount
                    End If
                    oCount += 1
                Next
                If USER_LANGUAGE = "de-DE" Then
                    Me.Text = CURRENT_DT_SELECTED_FILES.Rows.Count.ToString & " Datei(en) mit Datensatz verknüpfen:"
                Else
                    Me.Text = "Link " & CURRENT_DT_SELECTED_FILES.Rows.Count.ToString & " files with record:"
                End If
                ' Den index der aktuell geöffneten ConstructorForm setzen
                cmbConstructorForms.SelectedIndex = oSelectedIndex

            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error in frmDocRecordLink_Load", ex.Message, ex.StackTrace)
            End Try

            Load_DocGrid_Layout()
            bsiInfo.Caption = "Waiting for record-Selection....."

        End If

    End Sub
    Private Function GetENTITIES() As DataTable
        Try
            Dim SQL As String = String.Format("SELECT DISTINCT FORM_ID,FORM_TITLE,SEQUENCE FROM VWPMO_CONSTRUCTOR_FORMS where CONSTRUCT_ID in " &
"(SELECT CONSTRUCT_ID FROM TBPMO_CONSTRUCTOR_USER WHERE USER_ID = {0}) ORDER BY SEQUENCE", USER_GUID)
            Dim dt As DataTable = MYDB_ECM.GetDatatable(SQL)
            Return dt
        Catch ex As Exception
            MsgBox("Entities could not be loaded in LinkToRecord: " & vbNewLine & ex.Message)
            Return Nothing
        End Try
    End Function

    Private Sub grvwGrid_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles grvwGrid.FocusedRowChanged
        Try
            If Not IsNothing(dgEntityRecords.DataSource) Then
                Dim RecordId As Integer = grvwGrid.GetFocusedRowCellValue(grvwGrid.Columns("Record-ID"))

                bsiInfo.Caption = "Record (" & RecordId.ToString & ") selected!"
            End If
        Catch ex As Exception
            MsgBox("Could not get the RecordID: " & ex.Message, MsgBoxStyle.Exclamation)

        End Try

    End Sub
    Sub Save_DocGrid_Layout()
        Try
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            grvwGrid.SaveLayoutToXml(XMLPath)
            bsiInfo.Caption = "Grid-Layout saved - " + Now.ToShortTimeString

        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error in Save_DocGrid_Layout", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Sub Load_DocGrid_Layout()
        Try
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            If File.Exists(XMLPath) Then
                grvwGrid.RestoreLayoutFromXml(XMLPath)
                grvwGrid.GuessAutoFilterRowValuesFromFilter()
                bsiInfo.Caption = "Grid-Layout loaded - " + Now.ToShortTimeString

            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error in Load_DocGrid_Layout", ex.Message, ex.StackTrace)
        End Try
    End Sub
    Private Function Get_DocGrid_Layout_Filename()
        Dim Filename As String = String.Format("GridViewDocRecordLink-{0}-UserLayout.xml", CURRENT_LINK_ENTITY_ID)
        Return System.IO.Path.Combine(Application.UserAppDataPath(), Filename)
    End Function
    Private Sub frmDocRecordLink_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If ENTITY_LOAD_ACTIVE = False Then Save_DocGrid_Layout()
    End Sub

    Private Sub btnloadData2Entity_Click(sender As Object, e As EventArgs) Handles btnloadData2Entity.Click
        Dim entity As ClassEntity = DirectCast(cmbConstructorForms.SelectedItem, ClassEntity)
        Me.Cursor = Cursors.WaitCursor
        If cmbConstructorForms.SelectedIndex <> -1 Then
            ENTITY_LOAD_ACTIVE = True
            Save_DocGrid_Layout()
            Dim DT_RESULT = ReturnDataforEntity(entity.id)
            If Not IsNothing(DT_RESULT) Then
                CURRENT_LINK_ENTITY_ID = entity.id
                txtcurrSichtData.Text = entity.title
                Refresh_Grid_Data(False, DT_RESULT)
            End If
        End If
        Load_DocGrid_Layout()
        Me.Cursor = Cursors.Default
    End Sub
    Private Function ReturnDataforEntity(oEntityID As Integer) As DataTable
        Dim ResultSQL, ResultViewName As String
        LOGGER.Debug("GridType = Grid")
        ResultViewName = $"VWPMO_ENTITY_TABLE{oEntityID}"

        ResultSQL = $"SELECT T.* FROM {ResultViewName} T"
        LOGGER.Debug("ResultSQL: " & ResultSQL)
        Return MYDB_ECM.GetDatatable(ResultSQL)
    End Function

    Private Sub BarButtonItem1_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
        If clsWindream.Create_Session = False Then
            MsgBox("No session to windream created! Check Your connection!", MsgBoxStyle.Critical)
            Exit Sub
        End If

        Dim selectedRows As Integer() = grvwGrid.GetSelectedRows()
        Dim oLinkCount As Integer = 0
        For Each rowhandle As Integer In selectedRows
            Dim SELECTED_RECORDID = grvwGrid.GetRowCellValue(rowhandle, "Record-ID")
            If IsNothing(SELECTED_RECORDID) Then
                Continue For
            End If
            LOGGER.Debug(">>> Doc will be linked with Record: " & SELECTED_RECORDID.ToString)
            Try
                For Each row As DataRow In CURRENT_DT_SELECTED_FILES.Rows
                    CURRENT_DOC_ID = row.Item("DOC_ID")
                    Dim DOC_PATH = row.Item("FILEPATH")
                    Dim _objecttype = row.Item("OBJECTTYPE")
                    clsWindream.MY_WDOBJECTTYPE = _objecttype
                    Dim sql_Exec = String.Format("EXEC PRPMO_CHECK_DOC_RECORD_LINK {0},{1},'{2}','{3}'", SELECTED_RECORDID, CURRENT_DOC_ID, "MANUAL RECORD-LINK", USER_USERNAME)
                    'Dim ins = String.Format("INSERT INTO TBPMO_DOC_RECORD_LINK (RECORD_ID,DOC_ID,COMMENT,ADDED_WHO) VALUES ({0},{1},'{2}','{3}')", SELECTED_RECORDID, CURRENT_DOC_ID, "MANUAL RECORD-LINK", USER_USERNAME)
                    If MYDB_ECM.ExecuteNonQuery(sql_Exec) = False Then
                        MsgBox("Unexpected Error in Inserting Record-Doc Link. Please check logfile!", MsgBoxStyle.Critical)
                    Else
                        If LICENSE_PROXY = True And DD_LIB_Standards.clsDatabase.DB_PROXY_INITIALIZED Then
                            Dim proc = String.Format("EXEC PRPROXY_DOC_CHECK_DOC_REC_LINK {0},{1}", CURRENT_DOC_ID, SELECTED_RECORDID)
                            MYDB_ECM.ExecuteNonQuery(proc)
                        End If
                        Dim msg = String.Format("Der Datensatz wurde erfolgreich verknüpft!")
                        If USER_LANGUAGE <> "de-DE" Then
                            msg = "The record was successfully linked"
                        End If
                        bsiInfo.Caption = msg
                        ClassHelper.InsertEssential_Log(CURRENT_DOC_ID, "DOC-ID", "FILE LINK CREATED FOR RECORD: " & SELECTED_RECORDID.ToString)
                        oLinkCount += 1
                    End If
                    Dim sql = String.Format("SELECT * FROM TBPMO_WD_OBJECTTYPE WHERE OBJECT_TYPE = '{0}'", _objecttype)
                    Dim DT_OBJTYPE As DataTable = MYDB_ECM.GetDatatable(sql)
                    If DT_OBJTYPE.Rows.Count = 1 Then
                        Dim Entity_Index = DT_OBJTYPE.Rows(0).Item("IDXNAME_ENTITYID")
                        Dim Record_Index = DT_OBJTYPE.Rows(0).Item("IDXNAME_RECORDID")
                        Dim ENT_ID = MYDB_ECM.GetScalarValue(String.Format("SELECT FORM_ID FROM TBPMO_RECORD WHERE GUID = {0}", SELECTED_RECORDID))
                        If ENT_ID > 1 And Entity_Index <> String.Empty Then
                            clsWD_SET.IndexFile(DOC_PATH, Entity_Index, ENT_ID, _objecttype)
                        End If
                        If Record_Index <> String.Empty Then
                            clsWD_SET.IndexFile(DOC_PATH, Record_Index, SELECTED_RECORDID, _objecttype)
                        End If
                    End If
                Next
                bsiInfo.Caption = $"[{oLinkCount}] records successfully linked - {Now.ToShortTimeString}"

            Catch ex As Exception
                ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error in Linking Record to file", ex.Message, ex.StackTrace)
            End Try
        Next
        grvwGrid.ClearSelection()
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        Save_DocGrid_Layout()
    End Sub

    Private Sub BarButtonItem3_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem3.ItemClick
        Reset_View_layout()
    End Sub
    Sub Reset_View_layout()
        Me.Cursor = Cursors.WaitCursor
        Try
            Dim XMLPath = Get_DocGrid_Layout_Filename()
            If File.Exists(XMLPath) Then

                File.Delete(XMLPath)
                Refresh_Grid_Data(True, Nothing)
            Else
                MsgBox("Resetting the layout was not successful - File not existing!", MsgBoxStyle.Information)
            End If
        Catch ex As Exception
            ClassHelper.MSGBOX_Handler("ERROR", "Unexpected Error", "Error in Reset_View_layout: ", ex.Message)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub grvwGrid_StyleChanged(sender As Object, e As EventArgs) Handles grvwGrid.ColumnPositionChanged, grvwGrid.ColumnWidthChanged
        If ENTITY_LOAD_ACTIVE = False Then
            Save_DocGrid_Layout()
        End If
    End Sub

    Private Sub frmDocRecordLink_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        ENTITY_LOAD_ACTIVE = False
    End Sub
End Class