Imports System
Imports System.ComponentModel
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Text

Imports DevExpress.ExpressApp
Imports DevExpress.ExpressApp.Actions
Imports DevExpress.Persistent.Base
Imports DevExpress.ExpressApp.Model
Imports DevExpress.ExpressApp.Model.Core
Imports System.IO
Imports System.Xml
Imports DevExpress.Xpo
Imports DevExpress.Data.Filtering
Imports DevExpress.Persistent.BaseImpl


Public Class ListViewModelManagerVC
    Inherits DevExpress.ExpressApp.ViewController

    Public Sub New()
        MyBase.New()
        InitializeComponent()
        RegisterActions(components)
    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()

        If SecuritySystemHelper.IsUserInRoleCurrentUser("ListViewModelManager") = False Then
            Frame.GetController(Of ListViewModelManagerVC).aManageListViewModel.Active.SetItemValue("", False)
        End If

        If View.Id = "ListViewCustomization_DetailView" Then
            AddHandler Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DialogController)().AcceptAction.Executing, AddressOf ListViewCustomization_DetailView_AcceptAction_Executing
        End If

    End Sub
    Protected Overrides Sub OnDeactivated()
        MyBase.OnDeactivated()
        Frame.GetController(Of ListViewModelManagerVC).aManageListViewModel.Active.SetItemValue("", True)

        If View.Id = "ListViewCustomization_DetailView" Then
            RemoveHandler Frame.GetController(Of DevExpress.ExpressApp.SystemModule.DialogController)().AcceptAction.Executing, AddressOf ListViewCustomization_DetailView_AcceptAction_Executing
        End If
    End Sub

    Private Sub aManageListViewModel_CustomizePopupWindowParams(sender As Object, e As CustomizePopupWindowParamsEventArgs) Handles aManageListViewModel.CustomizePopupWindowParams
        Dim _onew As Xpo.XPObjectSpace = Application.CreateObjectSpace
        Dim _ListViewCustomization As ListViewCustomization

        _ListViewCustomization = _onew.CreateObject(Of ListViewCustomization)()
        e.View = Application.CreateDetailView(_onew, "ListViewCustomization_DetailView", True, _ListViewCustomization)

    End Sub
    Private Sub aManageListViewModel_Execute(sender As Object, e As PopupWindowShowActionExecuteEventArgs) Handles aManageListViewModel.Execute
        Dim _ListViewCustomization As ListViewCustomization = TryCast(e.PopupWindow.View.SelectedObjects(0), ListViewCustomization)
        View.SaveModel()

        Dim _Model As ModelApplicationBase = TryCast(Application.Model, ModelApplicationBase)

        Dim xmlWriter As New ModelXmlWriter()
        Dim aspect As String = _Model.GetAspect(0)
        Dim xmlContent As String = xmlWriter.WriteToString(_Model, 0)
        Dim _FileName As String = System.IO.Path.GetTempPath + View.Id + LTrim(RTrim(CStr(0))) + ".xml"

        Dim _StreamFile As System.IO.Stream = New System.IO.FileStream(_FileName, System.IO.FileMode.Create)
        Dim _StreamWriter As New StreamWriter(_StreamFile, System.Text.Encoding.UTF8)

        _StreamWriter.Write(xmlContent)
        _StreamWriter.Close()

        Select Case _ListViewCustomization.eEditMode
            Case eEditMode.eCentralXML
               

                If IO.File.Exists(_FileName) Then
                    Dim _XmlDocument_From As New XmlDocument
                    _XmlDocument_From.Load(_FileName)
                    Dim _ListViewNode_From As XmlNode = _XmlDocument_From.SelectSingleNode("/Application/Views/ListView[@Id='" + View.Id + "']")

                    Dim _XmlDocument_To As New XmlDocument
                    _XmlDocument_To.Load(_ListViewCustomization.XMLFileName)
                    Dim _ListViewNode_To As XmlNode = _XmlDocument_To.SelectSingleNode("/Application/Views/ListView[@Id='" + View.Id + "']")
                    Dim _ListViewNode_To_Parent As XmlNode = Nothing

                    If _ListViewNode_To IsNot Nothing Then
                        _ListViewNode_To_Parent = _ListViewNode_To.ParentNode
                        _ListViewNode_To.ParentNode.RemoveChild(_ListViewNode_To)
                        _XmlDocument_To.Save(_ListViewCustomization.XMLFileName)
                    Else
                        _ListViewNode_To_Parent = _XmlDocument_To.SelectSingleNode("/Application/Views")
                    End If
                    Dim _ListViewNode_To_ImportNode As XmlNode = _XmlDocument_To.ImportNode(_ListViewNode_From, True)
                    _ListViewNode_To_Parent.AppendChild(_ListViewNode_To_ImportNode)
                    _XmlDocument_To.Save(_ListViewCustomization.XMLFileName)
                End If
            Case eEditMode.eUserXML
                Dim _Session As New Session

                _Session.ConnectionString = GetConnectionString(_ListViewCustomization)
                _Session.Connect()
                If _Session.IsConnected Then
                    _Session.BeginTransaction()
                    Dim _XmlUser As XmlUser = _Session.FindObject(Of XmlUser)(CriteriaOperator.Parse("User=?", _Session.GetObjectByKey(Of User)(_ListViewCustomization.User.Oid)))
                    Dim _XmlStore As XmlStore = _Session.FindObject(Of XmlStore)(CriteriaOperator.Parse("User=?", _Session.GetObjectByKey(Of XmlUser)(_XmlUser.Oid)))
                    Dim _FileStream As FileStream = File.Create(IO.Path.GetTempPath + View.Id + ".xml")
                    Dim info As Byte() = New UTF8Encoding(True).GetBytes(_XmlStore.XmlData)
                    _FileStream.Write(info, 0, info.Length)
                    _FileStream.Close()

                    Dim _XmlDocument_To As New XmlDocument
                    _XmlDocument_To.Load(IO.Path.GetTempPath + View.Id + ".xml")
                    Dim _ListViewNode_To As XmlNode = _XmlDocument_To.SelectSingleNode("/Application/Views/ListView[@Id='" + View.Id + "']")
                    Dim _ListViewNode_To_Parent As XmlNode = Nothing

                    If _ListViewNode_To IsNot Nothing Then
                        _ListViewNode_To_Parent = _ListViewNode_To.ParentNode
                        _ListViewNode_To.ParentNode.RemoveChild(_ListViewNode_To)
                        _XmlDocument_To.Save(IO.Path.GetTempPath + View.Id + ".xml")
                    Else
                        _ListViewNode_To_Parent = _XmlDocument_To.SelectSingleNode("/Application/Views")
                    End If

                    Dim _XmlDocument_From As New XmlDocument
                    _XmlDocument_From.Load(_FileName)
                    Dim _ListViewNode_From As XmlNode = _XmlDocument_From.SelectSingleNode("/Application/Views/ListView[@Id='" + View.Id + "']")

                    Dim _ListViewNode_To_ImportNode As XmlNode = _XmlDocument_To.ImportNode(_ListViewNode_From, True)
                    _ListViewNode_To_Parent.AppendChild(_ListViewNode_To_ImportNode)
                    _XmlDocument_To.Save(IO.Path.GetTempPath + View.Id + ".xml")

                    _XmlStore.XmlData = _XmlDocument_To.InnerXml
                    _XmlStore.Save()
                    _Session.CommitTransaction()
                End If
        End Select
    End Sub
    Private Sub aListViewModelManager_FileBrowser_Execute(sender As Object, e As SimpleActionExecuteEventArgs) Handles aListViewModelManager_FileBrowser.Execute
        Dim _ListViewCustomization As ListViewCustomization = TryCast(View.SelectedObjects(0), ListViewCustomization)
        If _ListViewCustomization IsNot Nothing Then
            Dim _OpenFileDialog As New Windows.Forms.OpenFileDialog
            _OpenFileDialog.Filter = "XAFML file (.xafml)|*.xafml|All Files (*.*)|*.*"

            If _OpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
                _ListViewCustomization.XMLFileName = _OpenFileDialog.FileName
            End If
        End If
    End Sub
    Private Sub ListViewCustomization_DetailView_AcceptAction_Executing(sender As Object, e As CancelEventArgs)
        Dim _ListViewCustomization As ListViewCustomization = TryCast(View.SelectedObjects(0), ListViewCustomization)
        If String.IsNullOrEmpty(_ListViewCustomization.XMLFileName) And _ListViewCustomization.eEditMode = eEditMode.eCentralXML Then
            e.Cancel = True
            MsgBox("Nincs kiválasztva Model XML file!")
        ElseIf Not IO.File.Exists(_ListViewCustomization.XMLFileName) And _ListViewCustomization.eEditMode = eEditMode.eCentralXML Then
            e.Cancel = True
            MsgBox("A kiválasztott Model XML file nem létezik!")
        End If
    End Sub
    Private Function GetConnectionString(_ListViewCustomization As ListViewCustomization)
        Dim _ConnectionString As String = ""
        Select Case _ListViewCustomization.SQLType
            Case eSQLType.MSSQL
                _ConnectionString = DevExpress.Xpo.DB.MSSqlConnectionProvider.GetConnectionString(_ListViewCustomization.SQLServer, _ListViewCustomization.SQLUser, _ListViewCustomization.SQLPassword, _ListViewCustomization.SQLDatabase)
            Case eSQLType.MySQL
                _ConnectionString = DevExpress.Xpo.DB.MySqlConnectionProvider.GetConnectionString(_ListViewCustomization.SQLServer, _ListViewCustomization.SQLUser, _ListViewCustomization.SQLPassword, _ListViewCustomization.SQLDatabase)
            Case eSQLType.PostgreSQL
                _ConnectionString = DevExpress.Xpo.DB.PostgreSqlConnectionProvider.GetConnectionString(_ListViewCustomization.SQLServer, _ListViewCustomization.SQLUser, _ListViewCustomization.SQLPassword, _ListViewCustomization.SQLDatabase)
        End Select

        Return _ConnectionString
    End Function
End Class
