Imports System
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text
Imports System.Security
Imports System.Security.Permissions
Imports DevExpress.ExpressApp
Imports DevExpress.ExpressApp.Actions
Imports DevExpress.Persistent.Base
Imports DevExpress.ExpressApp.Win.SystemModule
Imports DevExpress.ExpressApp.ValidateObjectEventArgs
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.ExpressApp.Editors
Imports DevExpress.ExpressApp.Win.Editors
Imports DevExpress.ExpressApp.Security
Imports DevExpress.XtraGrid.Columns
Imports DevExpress.Data
Imports DevExpress.ExpressApp.FileAttachments.Win
Imports System.Reflection

Imports Nuvolar.Module
Imports DevExpress.Data.Filtering
Imports DevExpress.ExpressApp.Model
Imports DevExpress.Xpo

Public Class ContractsVC
    Inherits DevExpress.ExpressApp.ViewController
    Private _GridListEditor As GridListEditor
    Private _RichEditControl As RichEditControl
    Private _Contracts As Contracts
    Public Sub New()
        MyBase.New()
        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)
    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        Frame.GetController(Of WinModificationsController).ModificationsHandlingMode = SystemModule.ModificationsHandlingMode.AutoRollback
        If View.Id Like "Contracts_ListView*" Or View.Id Like "Contract*LookupListView" Then
            Frame.GetController(Of FileAttachmentListViewController)().Active.SetItemValue("", False)
        End If
        If View.Id = "Contracts_DetailView" Then
            _Contracts = TryCast(View.SelectedObjects(0), Contracts)
            Dim _DetailView As DetailView = TryCast(View, DetailView)
            Dim _RichEditContolViewItem As ViewItem = _DetailView.FindItem("DocumentBody")
            If _RichEditContolViewItem IsNot Nothing Then
                AddHandler _RichEditContolViewItem.ControlCreated, AddressOf RichEditContolViewItem_ControlCreated
            End If
        End If

    End Sub
    Protected Overrides Sub OnViewControlsCreated()
        MyBase.OnViewControlsCreated()
        If View.Id = "Contracts_ListView" Then
            Frame.GetController(Of FileAttachmentListViewController)().Active.SetItemValue("", True)
        End If
    End Sub
    Sub InitQTT_ProcessColumn()
        For i As Integer = 0 To _GridListEditor.Columns.Count - 1
            Dim _ColumnWrapper As ColumnWrapper = _GridListEditor.Columns(i)
            If _ColumnWrapper.PropertyName = "QTT" Then
                Dim _QTTColumn As GridColumn = _GridListEditor.GridView.Columns("QTT")
                _QTTColumn.OptionsColumn.AllowEdit = True
                _QTTColumn.OptionsColumn.AllowFocus = True
                _QTTColumn.OptionsColumn.ReadOnly = False
                _QTTColumn.UnboundType = UnboundColumnType.Decimal
            End If
            If _ColumnWrapper.PropertyName = "Units" Then
                Dim _UnitsColumn As GridColumn = _GridListEditor.GridView.Columns("Units")
                _UnitsColumn.OptionsColumn.AllowEdit = True
                _UnitsColumn.OptionsColumn.AllowFocus = True
                _UnitsColumn.OptionsColumn.ReadOnly = False
                _UnitsColumn.UnboundType = UnboundColumnType.Object
            End If
            Exit For
        Next
    End Sub
    Sub view_selectionchanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim _view = TryCast(View, ListView)
        _GridListEditor = TryCast(_view.Editor, GridListEditor)
        If _GridListEditor IsNot Nothing Then
            InitQTT_ProcessColumn()
        End If
    End Sub
    Public Sub _gridView_SelectionChanged(ByVal sender As Object, ByVal e As DevExpress.Data.SelectionChangedEventArgs)
        Dim _GridView As GridView = TryCast(sender, GridView)
        Dim _Contracts As Contracts
        If View.SelectedObjects.Count = 1 Then
            _Contracts = TryCast(View.SelectedObjects(0), Contracts)
            If Not _Contracts Is Nothing Then
                If _Contracts.State = State.Ready Or _Contracts.State = State.Signed Then
                    Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
                End If
            End If
        Else
            Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DeleteObjectsViewController).Active.SetItemValue("", False)
        End If
    End Sub

    Private Sub aContractsRTFRestoreTemplate_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aContractsRTFRestoreTemplate.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _Contracts As Contracts = TryCast(View.SelectedObjects(0), Contracts)

        If _Contracts IsNot Nothing Then
            If _Contracts.ContractTemplate IsNot Nothing Then
                _Contracts.DocumentBody = _Contracts.ContractTemplate.DocumentBody
            End If
        End If

    End Sub
    Private Sub aContractsRTFReplaceValue_Execute(sender As System.Object, e As DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs) Handles aContractsRTFReplaceValue.Execute
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _Contracts As Contracts = TryCast(View.SelectedObjects(0), Contracts)

        Dim _APCSheetByProducts As APCSheetByProducts = Nothing
        If _Contracts.ContractTemplate.IsAPCSheet Then
            _APCSheetByProducts = _ocur.FindObject(Of APCSheetByProducts)(CriteriaOperator.Parse("Contracts=?", _Contracts))
        End If

        Dim _Fields As DevExpress.XtraRichEdit.API.Native.FieldCollection = _RichEditControl.Document.Fields

        Dim _ContractsProperties As New ArrayList
        _ContractsProperties.AddRange(TryCast(_Contracts.[GetType](), System.Type).GetProperties())
        Dim _TemplateFields As New ArrayList
        For Each _Field As DevExpress.XtraRichEdit.API.Native.Field In _Fields
            _Field.ShowCodes = True
            Dim _ActString As String = _RichEditControl.Document.GetText(_Field.CodeRange)
            If Not _ActString.Contains("FORMTEXT") Then
                _TemplateFields.Add(_ActString.Replace("DOCVARIABLE ", ""))
            Else
                _TemplateFields.Add(_ActString)
            End If
        Next

        Dim _TemplateFieldsValue As New ArrayList
        For Each _ActTemplateField As String In _TemplateFields
            Dim _FiledLocation() As String = _ActTemplateField.Split(New Char() {"."c}, StringSplitOptions.RemoveEmptyEntries)
            If _FiledLocation.Length > 0 Then
                If _FiledLocation(0) = "APCSheetByProducts" Then
                    _TemplateFieldsValue.Add(FieldValue(_FiledLocation, Nothing, _APCSheetByProducts))
                ElseIf _FiledLocation(0) = "Contracts" Then
                    _TemplateFieldsValue.Add(FieldValue(_FiledLocation, _Contracts, Nothing))
                Else
                    _TemplateFieldsValue.Add(FieldValue(_FiledLocation, _Contracts, _APCSheetByProducts))
                End If
            End If
        Next

        Dim _FieldIndex As Int16 = 0
        _RichEditControl.BeginUpdate()
        Dim _Document As DevExpress.XtraRichEdit.API.Native.Document = _RichEditControl.Document
        _Document.BeginUpdate()

        For Each _ActTemplateField As String In _TemplateFields
            Dim field As DevExpress.XtraRichEdit.API.Native.Field = _Fields(_FieldIndex)
            field.ShowCodes = True
            Dim _FieldCode As String = _Document.GetText(field.CodeRange)
            Dim _FieldResult As String = _TemplateFieldsValue(_FieldIndex).ToString
            Dim _FieldPosition As DevExpress.XtraRichEdit.API.Native.DocumentPosition = field.Range.Start
            _Document.InsertText(_FieldPosition, _FieldResult)
            _FieldIndex += 1
        Next

        For ik = _Document.Fields.Count - 1 To 0 Step -1
            Dim field As DevExpress.XtraRichEdit.API.Native.Field = _Fields(ik)
            _Document.Delete(field.Range)
        Next

        _Document.EndUpdate()
        _RichEditControl.EndUpdate()
    End Sub
    Private Function FieldValue(_FiledLocation As String(), _Contracts As Contracts, _APCSheetByProducts As APCSheetByProducts) As String
        Dim _Value As String = ""
        Dim _ObjectType As Type = Nothing
        Dim _Object As Object = Nothing
        Dim _ikStart As Long = 0

        Try

        
        If _Contracts Is Nothing And _APCSheetByProducts Is Nothing Then
            _Value = "[Nincs beállítva]"
        ElseIf _Contracts IsNot Nothing And _APCSheetByProducts Is Nothing Then
            _ObjectType = _Contracts.[GetType]()
            _Object = _Contracts
            _ikStart = 1
        ElseIf _Contracts Is Nothing And _APCSheetByProducts IsNot Nothing Then
            _ObjectType = _APCSheetByProducts.[GetType]()
            _Object = _APCSheetByProducts
            _ikStart = 1
        Else
            _ObjectType = _Contracts.[GetType]()
            _Object = _Contracts
            _ikStart = 0
        End If

        If String.IsNullOrEmpty(_Value) Then
            For _ik = _ikStart To _FiledLocation.Length - 1
                If _ik < _FiledLocation.Length - 1 Then

                    Dim _PropertyInfo As PropertyInfo = _ObjectType.GetProperty(_FiledLocation(_ik))

                    If _PropertyInfo IsNot Nothing Then
                    _Object = _PropertyInfo.GetValue(_Object, Nothing)
                    If _Object IsNot Nothing Then
                        _ObjectType = _Object.[GetType]()
                    Else
                        _Value = "[Nincs beállítva]"
                        End If
                    Else
                        _Value = "[Nincs beállítva]"
                    End If
                Else
                    Dim _PropertyInfo As PropertyInfo = _ObjectType.GetProperty(_FiledLocation(_ik))

                    If _PropertyInfo IsNot Nothing Then
                        _Object = _PropertyInfo.GetValue(_Object, Nothing)
                        If _Object IsNot Nothing Then

                            If TryCast(_Object, IList) IsNot Nothing Then

                                For Each _ListElement In TryCast(_Object, IList)
                                    _Value += _ListElement.ToString & " "
                                Next
                            Else
                                _Value = _Object.ToString

                                Dim _IModelClass As IModelClass = Application.Model.BOModel.GetNode(_ObjectType.FullName)
                                For Each _OwnMembers In _IModelClass.OwnMembers

                                    If TryCast(_OwnMembers, IModelMember) IsNot Nothing Then
                                        If TryCast(_OwnMembers, IModelMember).Name = _PropertyInfo.Name Then
                                            Try
                                                If LTrim(RTrim(TryCast(_OwnMembers, IModelMember).DisplayFormat)) <> "" Then
                                                    _Value = String.Format(TryCast(_OwnMembers, IModelMember).DisplayFormat, _Object)
                                                End If
                                            Catch ex As Exception

                                            End Try
                                        End If
                                    End If
                                Next
                            End If
                        Else
                            _Value = "[Nincs beállítva]"
                        End If
                    Else
                        _Value = "[Nincs beállítva]"
                    End If
                End If
            Next
        End If
        Catch ex As Exception

        End Try
        Return _Value
    End Function
    Sub RecursivePropertyInfo(_Property_In As Object, _ArrayList_Value_In As ArrayList, _TagArray_In As String(), _TagArrayIndex As Int16, _ValueIndex_In As Int16)
        If _Property_In IsNot Nothing Then
            Dim _ObjctType As Type = _Property_In.[GetType]()

            For Each _PropertyInfo_In As PropertyInfo In _ObjctType.GetProperties()
                Dim _TagArrayIndex_new As Int16 = 0
                If _TagArray_In.Length = 2 Then
                    _TagArrayIndex_new = 1
                Else
                    _TagArrayIndex_new = _TagArrayIndex + 1
                End If
                If _PropertyInfo_In.Name = _TagArray_In(_TagArrayIndex_new) Then

                    If _TagArray_In.Length - 1 = _TagArrayIndex + 1 Then
                        _ArrayList_Value_In.Add(_PropertyInfo_In.GetValue(_Property_In, Nothing))
                        Exit For
                    Else
                        RecursivePropertyInfo(_PropertyInfo_In.GetValue(_Property_In, Nothing), _ArrayList_Value_In, _TagArray_In, _TagArrayIndex + 1, _ValueIndex_In)
                        Exit For
                    End If
                End If
            Next
            If _ArrayList_Value_In.Count < _ValueIndex_In Then _ArrayList_Value_In.Add(TagBuilder(_TagArray_In))
        Else
            _ArrayList_Value_In.Add(TagBuilder(_TagArray_In))
        End If
    End Sub
    Function TagBuilder(_TagArray_In As String()) As String
        Dim _ActTag As New StringBuilder
        _ActTag.Append("[")
        For Each _TTag As String In _TagArray_In
            _ActTag.Append(_TTag + ".")
        Next
        _ActTag.Append("]")
        Return (_ActTag.ToString).Remove(_ActTag.ToString.Length - 2, 1)
    End Function
    '((_PropertyInfo_In.GetValue(_Property_In, Nothing)).[GetType]()).GetProperties().Length > 0 And
    'If (((_PropertyInfo_In.GetValue(_Property_In, Nothing)).[GetType]().ToString.Split(New Char() {"."c}, StringSplitOptions.RemoveEmptyEntries)))(0) = "Nuvolar" Then
    '    RecursivePropertyInfo(_PropertyInfo_In.GetValue(_Property_In, Nothing), _RecursionLevel + 1, _ArrayList_Name_In, _ArrayList_Value_In)
    'End If
    Private Sub RichEditContolViewItem_ControlCreated(sender As Object, e As EventArgs)
        Dim _ItemControl As Object = TryCast(sender, ViewItem).Control
        Dim _RichEditUserControl As RichEditUserControl = TryCast(_ItemControl, RichEditUserControl)
        _RichEditControl = TryCast(_ItemControl, RichEditUserControl).RichEditControl
    End Sub

    Private Sub aInsertRTFTextContracts_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aInsertRTFTextContracts.Execute
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        Dim _User As DevExpress.Persistent.BaseImpl.User = _onew.GetObjectByKey(Of DevExpress.Persistent.BaseImpl.User)(_onew.GetKeyValue(SecuritySystem.CurrentUser))
        Dim _RTFCopy As RTFCopy = _onew.FindObject(Of RTFCopy)(CriteriaOperator.Parse("UserCreated=?", _User))
        Dim _Contracts As Contracts = TryCast(View.SelectedObjects(0), Contracts)

        Dim _DocPos As API.Native.DocumentPosition = _RichEditControl.Document.CaretPosition

        _RichEditControl.Document.InsertHtmlText(_DocPos, _RTFCopy.RTFString)
    End Sub
End Class