Imports System.ComponentModel
Imports System.Threading
Imports DevExpress.Xpf.Core

Public Class VentanaProgreso
    Public IVentana As IVentanaProgreso
    Private AutoResetEvent As New AutoResetEvent(False)
    Dim worker As New BackgroundWorker
    Public Cancelar As Boolean
    Dim TareasProgreso As New List(Of TareaProgreso)
    Public MensajeError As String
    'Private _UltimaLinea As TareaProgreso
    'Property UltimaLinea As TareaProgreso
    '    Get
    '        Return _UltimaLinea
    '    End Get
    '    Set(value As TareaProgreso)
    '        _UltimaLinea = value
    '        RaisePropertyChanged("UltimaLinea")
    '    End Set
    'End Property


    'Public PropertyChanged As PropertyChangedEventHandler

    'Protected Overloads Sub RaisePropertyChanged(propertyName As String)
    '    Dim handler As PropertyChangedEventHandler = Me.PropertyChanged
    '    If handler IsNot Nothing Then
    '        Dim e = New PropertyChangedEventArgs(propertyName)
    '        handler(Me, e)
    '    End If
    'End Sub

    Private Sub Window_ContentRendered(sender As Object, e As EventArgs)
        ' DevExpress.Xpf.Core.DXGridDataController.DisableThreadingProblemsDetection = True
        worker.WorkerReportsProgress = True
        worker.WorkerSupportsCancellation = True
        AddHandler worker.DoWork, AddressOf worker_dowork
        AddHandler worker.ProgressChanged, AddressOf worker_ProgressChanged
        AddHandler worker.RunWorkerCompleted, AddressOf worker_RunWorkerCompleted
        worker.RunWorkerAsync()
        'AutoResetEvent.WaitOne()
    End Sub

    Private Sub worker_dowork(sender As Object, e As DoWorkEventArgs)
        Try
            IVentana.IniciarTareas(sender)
            Me.AutoResetEvent.Set()

        Catch ex As Exception
            Throw New Exception(ex.Message, ex)
            ' DXMessageBox.Show(ex.Message, "Atención")
        End Try
    End Sub

    Private Sub worker_ProgressChanged(sender As Object, e As ProgressChangedEventArgs)
        Select Case e.UserState.GetType
            Case GetType(TareaProgreso)
                Me.ProgresoGeneral.EditValue = e.ProgressPercentage
                Dim tp As TareaProgreso = e.UserState
                Select Case tp.Tipo
                    Case TiposTareaProgresoEnum.LIMPIAR_FILAS
                        TareasProgreso.Clear()
                        Me.gc.RefreshData()
                    Case TiposTareaProgresoEnum.NUEVA_FILA
                        Dim tpe = TareasProgreso.Where(Function(t) t.id = tp.id)
                        If tpe.Count = 0 Then
                            Dim ntp As New TareaProgreso With {
                                .id = tp.id,
                                .Descripcion = tp.Descripcion,
                                .FechaInicio = tp.FechaInicio,
                                .Progreso = tp.Progreso}
                            tv.ScrollIntoView(gc.GetRowByListIndex(gc.VisibleRowCount - 1))
                            TareasProgreso.Add(ntp)
                        Else
                            tpe.First.Progreso = tp.Progreso
                            tpe.First.Descripcion = tp.Descripcion
                        End If
                        Me.gc.RefreshData()
                    Case TiposTareaProgresoEnum.CAMBIO_TITULO
                        Me.Title = tp.Descripcion
                    Case TiposTareaProgresoEnum.EXCEPCION
                        If Not Cancelar Then
                            Me.MensajeError = tp.Descripcion
                            Cancelar = True
                            Me.worker.CancelAsync()
                            Me.AutoResetEvent.WaitOne()
                        End If
                    Case TiposTareaProgresoEnum.FINALIZAR
                        Cancelar = False
                End Select
            Case GetType([Delegate])
                Dim proceso As [Delegate] = e.UserState

        End Select

    End Sub

    Private Sub btCancelar_Click(sender As Object, e As RoutedEventArgs)
        Cancelar = IVentana.Cancelar 'true
        If Cancelar Then
            Me.worker.CancelAsync()
            Me.AutoResetEvent.WaitOne()
        End If
    End Sub

    Private Sub worker_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs)
        'Me.DialogResult = Not (Cancelar)
        '  DirectCast(sender, BackgroundWorker).Dispose()
        Me.Close()

    End Sub

    Private Sub VentanaProgreso_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        Me.gc.ItemsSource = TareasProgreso
    End Sub

    Public Sub New()

        ' Llamada necesaria para el diseñador.
        Cancelar = False
        InitializeComponent()

        ' Agregue cualquier inicialización después de la llamada a InitializeComponent().

    End Sub
End Class
Public Class TareaProgreso
    Property id As Integer
    Property Tipo As TiposTareaProgresoEnum    
    Property FechaInicio As DateTime
    Property Descripcion As String
    Property Progreso As Integer

End Class
Public Enum TiposTareaProgresoEnum
    LIMPIAR_FILAS
    NUEVA_FILA
    CAMBIO_TITULO
    EXCEPCION
    FINALIZAR
End Enum
