Public Class frmTemplates
    Dim _TEMPLATEID As Integer
    Dim _TEMPLATE_ENTITY_ID As Integer
    Dim _ENTITY_ID As Integer
    Dim loaded As Boolean = False
    Private Sub frmTemplates_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Me.TBPMO_TEMPLATETableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_TEMPLATE_ENTITYTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_TEMPLATE_PATTERNTableAdapter.Connection.ConnectionString = MyConnectionString
        Catch ex As Exception
            MsgBox("Unexpected error in Load Form:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        Try
            DD_DMSDataSet.TBPMO_TEMPLATE.ADDED_WHOColumn.DefaultValue = Environment.UserName
            DD_DMSDataSet.TBPMO_TEMPLATE_ENTITY.ADDED_WHOColumn.DefaultValue = Environment.UserName
            DD_DMSDataSet.TBPMO_TEMPLATE_PATTERN.ADDED_WHOColumn.DefaultValue = Environment.UserName
        Catch ex As Exception

        End Try
        'Wertehilfen laden
        Load_Doctypes()
        Load_Entities()

        Load_Templates()

    End Sub
    Sub Load_Templates()
        Try
            Me.TBPMO_TEMPLATETableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_TEMPLATE)
        Catch ex As Exception
            MsgBox("Unexpected error in Load Templates:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Template_Entity(ID As Integer)
        Try
            Dim sql As String = "SELECT T.GUID, T2.FORM_TITLE, T.ENTITY_ID FROM TBPMO_TEMPLATE_ENTITY T, TBPMO_FORM T1, TBPMO_FORM_VIEW T2 " & _
            "WHERE T.ENTITY_ID = T1.GUID And T1.GUID = T2.FORM_ID And T2.SCREEN_ID = 1 And T.TEMPLATE_ID = " & ID
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "Load_Template_Entity")
            If DT.Rows.Count > 0 Then
                ListBox_Entity.DataSource = DT
                    ListBox_Entity.DisplayMember = DT.Columns(1).ColumnName
                ListBox_Entity.ValueMember = DT.Columns(0).ColumnName
                ListBox_Entity.SelectedIndex = 0
            End If
        Catch ex As Exception
            MsgBox("Unexpected error in Load Template-Entities:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
  
    Private Sub TBPMO_TEMPLATEBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBPMO_TEMPLATEBindingSource.CurrentChanged
        lblSaveTemplate.Visible = False
        lblSaveEntity.Visible = False
        Load_entity()
    End Sub
    Sub Load_Template_Patterns(ID As Integer)
        Try
            Me.TBPMO_TEMPLATE_PATTERNTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_TEMPLATE_PATTERN, ID)
            Dim DT1 As DataTable = ClassDatabase.Return_Datatable("SELECT [CONTROL_ID] ,CONTROL_COL_NAME AS DISPLAY FROM [VWPMO_CONTROL_SCREEN] WHERE CTRLTYPE_ID in (2,3,4) AND FORM_ID = " & _ENTITY_ID)
            cmbControls.DataSource = DT1
            cmbControls.DisplayMember = DT1.Columns(1).ColumnName
            cmbControls.ValueMember = DT1.Columns(0).ColumnName
            Get_CONTROL_COMBOBOX()
        Catch ex As Exception
            MsgBox("Unexpected error in Load Template-Patterns:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub frmTemplates_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        loaded = True
        Load_entity()
    End Sub
    Sub Load_entity()
        If GUIDTextBox.Text <> "" Then
            _TEMPLATEID = GUIDTextBox.Text
            Load_Template_Entity(_TEMPLATEID)
        End If
    End Sub
    Sub Load_Doctypes()
        Try
            VWPMO_DOKUMENTTYPESTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.VWPMO_DOKUMENTTYPESTableAdapter.FillBy(Me.DD_DMSDataSet.VWPMO_DOKUMENTTYPES)
        Catch ex As Exception
            MsgBox("Unexpected error in Load Doctypes:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub Load_Entities()
        Try
            VWPMO_GUI_ENTITYTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.VWPMO_GUI_ENTITYTableAdapter.Fill(Me.DD_DMSDataSet.VWPMO_GUI_ENTITY)
        Catch ex As Exception
            MsgBox("Unexpected error in Load Entities:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub TBPMO_TEMPLATEBindingNavigatorSaveItem_Click_1(sender As Object, e As EventArgs) Handles TBPMO_TEMPLATEBindingNavigatorSaveItem.Click
        Try
            Me.Validate()
            Me.TBPMO_TEMPLATEBindingSource.EndEdit()
            If Me.DD_DMSDataSet.TBPMO_TEMPLATE.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = Environment.UserName
                Me.TBPMO_TEMPLATEBindingSource.EndEdit()
                TBPMO_TEMPLATETableAdapter.Update(DD_DMSDataSet.TBPMO_TEMPLATE)
                lblSaveTemplate.Visible = True
            Else
                lblSaveTemplate.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Unexpected error in Save Template:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Private Sub btnAddTemplate_Click(sender As Object, e As EventArgs) Handles btnAddTemplate.Click
        If Not Me.TEMPLATE_PATHTextBox.Text = "" Then
            Me.OpenFileDialog1.FileName = Me.TEMPLATE_PATHTextBox.Text
        End If

        If Me.OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
            Me.TEMPLATE_PATHTextBox.Text = Me.OpenFileDialog1.FileName
            GetPatterns()
        End If
    End Sub
    Sub GetPatterns()
        Dim word As New Microsoft.Office.Interop.Word.Application
        Dim doc As New Microsoft.Office.Interop.Word.Document
        Try
            If DD_DMSDataSet.TBPMO_TEMPLATE_PATTERN.Rows.Count = 0 Then
                Dim result As MsgBoxResult
                result = MessageBox.Show("Wollen Sie die Platzhalter aus der Vorlage neu laden?", "Frage:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
                If result = MsgBoxResult.Yes Then
                    doc = word.Documents.Open(TEMPLATE_PATHTextBox.Text)
                    'doc.Activate()
                    ' word.Visible = (True) 'Word sichtbar

                    For Each cc In doc.ContentControls
                        If Not IsNothing(cc) Then
                            If LogErrorsOnly = False Then ClassLogger.Add(">> Office-Pattern: " & cc.Tag, False)
                            If Pattern_exists(cc.tag.ToString.ToUpper) = False Then
                                TBPMO_TEMPLATE_PATTERNTableAdapter.cmdInsertBasics(cc.tag.ToString, Environment.UserName, _TEMPLATE_ENTITY_ID)
                            End If
                        End If
                    Next cc

                    '  doc.ContentControls().Item("Name").Range.Text = "Schreiber"
                    'Textmarken füllen
                    '    doc.().Item("Name").Range.Text = "Schreiber"
                    'doc.Bookmarks().Item("Vorname").Range.Text = "Marlon"
                    'doc.Bookmarks().Item("Produktion").Range.Text = "Testproduktion"
                    'doc.Close()
                    'speichern / drucken
                    'doc.SaveAs("c:\Proforma.doc")
                    'doc.PrintOut()
                    doc.Close()
                    doc = Nothing
                    word.Quit()
                    MsgBox("Die Platzhalter wurden erfolgreich aktualisiert!", MsgBoxStyle.Information)
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpected error in Get/set Patterns:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            doc.Close()
            doc = Nothing
            word.Quit()
        End Try
        Load_Template_Patterns(_TEMPLATE_ENTITY_ID)
    End Sub
    Private Function Pattern_exists(name As String)
        Try
            Dim sql = "select count(*) from TBPMO_TEMPLATE_PATTERN where UPPER(NAME_PATTERN) = UPPER('" & name & "') AND TEMPLATE_ENT_ID = " & _TEMPLATE_ENTITY_ID
            Dim result = ClassDatabase.Execute_Scalar(sql, True)
            If IsNothing(result) Then
                Return False
            ElseIf result = 1 Then
                Return True
            ElseIf result = 0 Then
                Return False
            End If
        Catch ex As Exception
            MsgBox("Unexpected error in Pattern Exists:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
    End Function
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If cmbEntities.SelectedIndex <> -1 Then
            Try
                TBPMO_TEMPLATE_ENTITYTableAdapter.Insert(_TEMPLATEID, cmbEntities.SelectedValue, Environment.UserName)
                Load_Template_Entity(_TEMPLATEID)
                lblSaveEntity.Visible = True
            Catch ex As Exception
                MsgBox("Unexpected error in Add Template2Entity:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                lblSaveEntity.Visible = False
            End Try
        End If
    End Sub

    Private Sub btndeleteEntityZO_Click(sender As Object, e As EventArgs) Handles btndeleteEntityZO.Click
        Try
            TBPMO_TEMPLATE_ENTITYTableAdapter.Delete(ListBox_Entity.SelectedValue)
            Load_Template_Entity(_TEMPLATEID)
            lblSaveEntity.Visible = True
        Catch ex As Exception
            MsgBox("Unexpected error in Delete Template2Entity:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            lblSaveEntity.Visible = False
        End Try
    End Sub

    Private Sub ToolStripButton16_Click(sender As Object, e As EventArgs) Handles ToolStripButton16.Click
        Load_Template_Patterns(_TEMPLATE_ENTITY_ID)
    End Sub

    Private Sub ListBox_Entity_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox_Entity.SelectedIndexChanged
        _TEMPLATE_ENTITY_ID = ListBox_Entity.SelectedValue
        _ENTITY_ID = ClassDatabase.Execute_Scalar("SELECT ENTITY_ID FROM TBPMO_TEMPLATE_ENTITY WHERE GUID = " & _TEMPLATE_ENTITY_ID)
        Load_Template_Patterns(_TEMPLATE_ENTITY_ID)
    End Sub
    Private Sub ToolStripButton10_Click(sender As Object, e As EventArgs) Handles ToolStripButton10.Click
        TBPMO_TEMPLATE_PATTERNTableAdapter.Delete(ListBoxPatterns.SelectedValue)
        Load_Template_Patterns(_TEMPLATE_ENTITY_ID)
    End Sub

    Private Sub cmbControls_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbControls.SelectedIndexChanged
        If loaded = False Then Exit Sub
        If cmbControls.SelectedIndex <> -1 Then
            If cmbControls.Text <> "System.Data.DataRowView" Then
                Dim Sql = "select TOP 30 [" & cmbControls.Text & "] FROM VWTEMP_PMO_FORM" & _ENTITY_ID & " WHERE [" & cmbControls.Text & "] IS NOT NULL AND [" & cmbControls.Text & "] <> '' GROUP BY [" & cmbControls.Text & "]"
                Dim DT As DataTable = ClassDatabase.Return_Datatable(Sql)
                If DT.Rows.Count > 0 Then
                    ListBoxVorschau.DataSource = DT
                    ListBoxVorschau.DataSource = DT
                    ListBoxVorschau.DisplayMember = DT.Columns(0).ColumnName
                End If
                If FIXED_VALUETextBox.Text <> "" Then
                    Dim name = "SELECT COL_NAME FROM TBPMO_CONTROL WHERE GUID = " & FIXED_VALUETextBox.Text
                    name = ClassDatabase.Execute_Scalar(name, True)
                    If cmbControls.Text <> name Then
                        btnRefreshControlPattern.Visible = True
                    Else
                        btnRefreshControlPattern.Visible = False
                    End If
                Else
                    btnRefreshControlPattern.Visible = True
                End If
               
            End If
         
        End If
    End Sub

    Private Sub tsbtnGetPatterns_Click(sender As Object, e As EventArgs) Handles tsbtnGetPatterns.Click
        GetPatterns()
    End Sub

    Private Sub ToolStripButton15_Click(sender As Object, e As EventArgs) Handles ToolStripButton15.Click

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnRefreshControlPattern.Click
        If cmbControls.SelectedIndex <> -1 Then
            Dim ctrlstring = cmbControls.SelectedValue.ToString
            Dim sql = String.Format("UPDATE TBPMO_TEMPLATE_PATTERN SET FIXED_VALUE = '{0}',CHANGED_WHO = '{1}' WHERE GUID = {2}", ctrlstring, Environment.UserName, GUIDTextBox2.Text)
            If ClassDatabase.Execute_non_Query(sql, True) Then
                FIXED_VALUETextBox.Text = ctrlstring
                lblSavePattern.Visible = True
            Else
                lblSavePattern.Visible = False
            End If
        End If
    End Sub
    Private Sub TBPMO_TEMPLATE_PATTERNBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBPMO_TEMPLATE_PATTERNBindingSource.CurrentChanged
        If loaded = True Then
            Get_CONTROL_COMBOBOX()
            lblSavePattern.Visible = False

        End If
    End Sub
    Sub Get_CONTROL_COMBOBOX()
        If IsNumeric(FIXED_VALUETextBox.Text) Then
            Dim name = "SELECT COL_NAME FROM TBPMO_CONTROL WHERE GUID = " & FIXED_VALUETextBox.Text
            name = ClassDatabase.Execute_Scalar(name, True)
            cmbControls.SelectedIndex = cmbControls.FindStringExact(name)
        Else
            btnRefreshControlPattern.Visible = True
        End If
    End Sub
End Class