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.Xpo

Public Class RoundingController
    Inherits DevExpress.ExpressApp.ViewController(Of ListView)

    Public Sub New()
        MyBase.New()

        'This call is required by the Component Designer.
        InitializeComponent()
        RegisterActions(components)

    End Sub
    Protected Overrides Sub OnActivated()
        MyBase.OnActivated()
        Dim _SQL As String = ""
        Dim _ocur As Xpo.XPObjectSpace = TryCast(View.ObjectSpace, Xpo.XPObjectSpace)
        If View Is Nothing Then Exit Sub

        For Each _OwnMember In View.Model.ModelClass.OwnMembers
            Dim _IModelMemberAllowSort As IModelMemberAllowSort = TryCast(_OwnMember, IModelMemberAllowSort)
            If _IModelMemberAllowSort IsNot Nothing Then
                If _IModelMemberAllowSort.AllowRounding Then
                    Try
                        Select Case GLOBAL_SQLType
                            Case eSQLType.MySQL, eSQLType.MSSQL
                                _SQL = "UPDATE " & View.Model.ModelClass.ShortName.ToString & " SET " & _OwnMember.Name.ToString & "=ROUND(" & _OwnMember.Name.ToString
                                _SQL += "," & _IModelMemberAllowSort.RoundingTo.ToString & ") WHERE "
                                _SQL += _OwnMember.Name.ToString & "<>ROUND(" & _OwnMember.Name.ToString & "," & _IModelMemberAllowSort.RoundingTo.ToString & ")"

                                _ocur.Session.ExecuteNonQuery(_SQL)
                            Case eSQLType.PostgreSQL
                                _SQL = "UPDATE """ & View.Model.ModelClass.ShortName.ToString & """ SET """ & _OwnMember.Name.ToString & """=ROUND(""" & _OwnMember.Name.ToString
                                _SQL += """," & _IModelMemberAllowSort.RoundingTo.ToString & ") WHERE """
                                _SQL += _OwnMember.Name.ToString & """<>ROUND(""" & _OwnMember.Name.ToString & """," & _IModelMemberAllowSort.RoundingTo.ToString & ")"

                                _ocur.Session.ExecuteNonQuery(_SQL)
                        End Select
                    Catch exp As Exception
                        Dim _uow_exception As New UnitOfWork(_ocur.Session.DataLayer)
                        Dim _ErrorLog As ErrorLog = New ErrorLog(_uow_exception)
                        _ErrorLog.Description = exp.Message.ToString & " (" & _SQL & ")"
                        _ErrorLog.Save()
                        _uow_exception.CommitChanges()
                    End Try
                End If
            End If
        Next
    End Sub
End Class
