Imports DevExpress.Xpf.LayoutControl
Imports System.Data
Imports System.Globalization
Imports System.IO
Imports System.Reflection

Namespace Utilidades
    Public Class Varias

        Public Shared Function DatatableAListaDeHahstable(Tabla As DataTable) As List(Of Hashtable)
            Dim lht As New List(Of Hashtable)
            For i = 0 To Tabla.Rows.Count - 1
                Dim ht As New Hashtable
                For j = 0 To Tabla.Columns.Count - 1
                    ht.Add(Tabla.Columns(j).ColumnName, Tabla.Rows(i)(j).ToString)
                Next
                lht.Add(ht)
            Next
            Return lht
        End Function
        Public Shared Sub EstableceSoloLecturaRecursivo(Objeto As Object, SoloLectura As Boolean)
            For Each hijo In Objeto.Children
                If hijo.GetType Is GetType(Control) Then
                    hijo.isEnabled = Not SoloLectura
                ElseIf hijo.GetType Is GetType(LayoutGroup) Or hijo.GetType Is GetType(Grid) Then
                    EstableceSoloLecturaRecursivo(hijo, SoloLectura)
                End If
            Next
        End Sub

        Public Shared Function ByteArraytoBitmapImage(byteArray As [Byte]()) As BitmapImage
            Dim stream As New MemoryStream(byteArray)
            Dim bitmapImage As New BitmapImage()
            bitmapImage.StreamSource = stream
            Return bitmapImage
        End Function

        Public Shared Function StreamToBitmapImage(st As Stream) As BitmapImage
            Dim bitmapImage As New BitmapImage()
            bitmapImage.StreamSource = st
            Return bitmapImage
        End Function
        Public Shared Function PrevInstance() As Boolean
            Try
                If UBound(Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess.ProcessName)) > 0 Then
                    Return True
                Else
                    Return False
                End If
            Catch ex As Exception
                Return False
            End Try
        End Function

        Public Shared Function GeneraExpresionBusquedaNoNulos(TextoAbuscar As String, CamposBusquedaNumericos() As String, CamposBusquedaAlfabeticos() As String, CamposBusquedaAlfabeticosPorIgualdad() As String, Optional CamposBusquedaAlfabeticosPorComienzo() As String = Nothing, Optional TipoBusqueda As String = "and") As String
            Dim Expresion As String = ""
            If TipoBusqueda = "and" Then
                TipoBusqueda = "&&"
            Else
                TipoBusqueda = "||"
            End If

            Dim Palabras = TextoAbuscar.Trim.Split(" ").Where(Function(x) x.Trim <> "")
            If CamposBusquedaNumericos IsNot Nothing Then
                For Each palabra In Palabras
                    Dim Numero = palabra.Replace(",", ".")
                    If CamposBusquedaNumericos.Count > 0 AndAlso Double.TryParse(Numero, Nothing) Then
                        For Each c In CamposBusquedaNumericos
                            Expresion &= " || " & "(" & c & " !=null && " & c & "=" & Numero.TrimEnd(".") & ")"
                        Next
                    End If
                Next
            End If
            If CamposBusquedaAlfabeticos IsNot Nothing Then
                For Each c In CamposBusquedaAlfabeticos
                    Dim ExpresionParcial As String = ""
                    For Each palabra In Palabras
                        palabra = palabra.Replace(Chr(34), """" & """")
                        ExpresionParcial &= " " & TipoBusqueda & " " & "(" & c & " != null && " & c & ".Contains(" & Chr(34) & palabra & Chr(34) & "))"
                    Next
                    ExpresionParcial = "(" & ExpresionParcial.Substring(2 + TipoBusqueda.Length) & ")"
                    Expresion &= " || " & ExpresionParcial
                Next
            End If

            If CamposBusquedaAlfabeticosPorIgualdad IsNot Nothing Then
                Dim ExpresionParcial As String = ""
                For Each palabra In Palabras
                    If CamposBusquedaAlfabeticosPorIgualdad.Count > 0 Then
                        For Each c In CamposBusquedaAlfabeticosPorIgualdad
                            ExpresionParcial &= " || " & "(" & c & " != null && " & c & "=" & Chr(34) & palabra & Chr(34) & ")"
                        Next
                    End If
                Next
                ExpresionParcial = "(" & ExpresionParcial.Substring(2 + TipoBusqueda.Length) & ")"
                Expresion &= " || " & ExpresionParcial
            End If
            If CamposBusquedaAlfabeticosPorComienzo IsNot Nothing Then
                Dim ExpresionParcial As String = ""
                For Each palabra In Palabras
                    If CamposBusquedaAlfabeticosPorComienzo.Count > 0 Then
                        For Each c In CamposBusquedaAlfabeticosPorComienzo
                            ExpresionParcial &= " " & TipoBusqueda & " " & "(" & c & " != null && " & c & ".StartsWith(" & Chr(34) & palabra & Chr(34) & "))"
                        Next
                    End If
                Next
                ExpresionParcial = "(" & ExpresionParcial.Substring(2 + TipoBusqueda.Length) & ")"
                Expresion &= " || " & ExpresionParcial
            End If
            If Expresion <> "" Then
                Return Expresion.Substring(4)
            Else
                Return ""
            End If
        End Function
        Public Shared Function GeneraExpresionBusqueda(TextoAbuscar As String, CamposBusquedaNumericos() As String, CamposBusquedaAlfabeticos() As String, CamposBusquedaAlfabeticosPorIgualdad() As String, Optional CamposBusquedaAlfabeticosPorComienzo() As String = Nothing, Optional TipoBusqueda As String = "and") As String
            Dim Expresion As String = ""
            Dim Palabras = TextoAbuscar.Trim.Split(" ").Where(Function(x) x.Trim <> "")
            If CamposBusquedaNumericos IsNot Nothing Then
                For Each palabra In Palabras
                    Dim Numero = palabra.Replace(",", ".")
                    If CamposBusquedaNumericos.Count > 0 AndAlso Double.TryParse(Numero, Nothing) Then
                        For Each c In CamposBusquedaNumericos
                            Expresion &= " or " & c & "=" & Numero.TrimEnd(".")
                        Next
                    End If
                Next
            End If
            If CamposBusquedaAlfabeticos IsNot Nothing Then
                For Each c In CamposBusquedaAlfabeticos
                    Dim ExpresionParcial As String = ""
                    For Each palabra In Palabras
                        palabra = palabra.Replace(Chr(34), """" & """")
                        ExpresionParcial &= " " & TipoBusqueda & " " & c & ".Contains(" & Chr(34) & palabra & Chr(34) & ")"
                    Next
                    ExpresionParcial = "(" & ExpresionParcial.Substring(2 + TipoBusqueda.Length) & ")"
                    Expresion &= " or " & ExpresionParcial
                Next
            End If

            If CamposBusquedaAlfabeticosPorIgualdad IsNot Nothing Then
                Dim ExpresionParcial As String = ""
                For Each palabra In Palabras
                    If CamposBusquedaAlfabeticosPorIgualdad.Count > 0 Then
                        For Each c In CamposBusquedaAlfabeticosPorIgualdad
                            ExpresionParcial &= " or " & c & "=" & Chr(34) & palabra & Chr(34)
                        Next
                    End If
                Next
                ExpresionParcial = "(" & ExpresionParcial.Substring(4) & ")"
                Expresion &= " or " & ExpresionParcial
            End If
            If CamposBusquedaAlfabeticosPorComienzo IsNot Nothing Then
                Dim ExpresionParcial As String = ""
                For Each palabra In Palabras
                    If CamposBusquedaAlfabeticosPorComienzo.Count > 0 Then
                        For Each c In CamposBusquedaAlfabeticosPorComienzo
                            ExpresionParcial &= " " & TipoBusqueda & " " & c & ".StartsWith(" & Chr(34) & palabra & Chr(34) & ")"
                        Next
                    End If
                Next
                ExpresionParcial = "(" & ExpresionParcial.Substring(1 + TipoBusqueda.Length) & ")"
                Expresion &= " or " & ExpresionParcial
            End If
            If Expresion <> "" Then
                Return Expresion.Substring(4)
            Else
                Return ""
            End If
        End Function


        Public Shared Function GeneraExpresionBusqueda(TextoAbuscar As String, CamposBusquedaIntegers() As String, CamposBusquedaDoubles() As String, CamposBusquedaAlfabeticos() As String, CamposBusquedaAlfabeticosPorIgualdad() As String, ByRef Parametros() As Object, Optional CamposBusquedaAlfabeticosPorComienzo() As String = Nothing, Optional TipoBusqueda As String = "and") As String
            Dim Expresion As String = ""
            Dim Palabras = TextoAbuscar.Trim.Split(" ").Where(Function(x) x.Trim <> "")
            Dim ContNum As Integer = 0
            If CamposBusquedaIntegers IsNot Nothing Then
                For Each palabra In Palabras
                    Dim Numero = palabra.Replace(",", ".")
                    If Numero.Contains(".") = False AndAlso CamposBusquedaIntegers.Count > 0 AndAlso Integer.TryParse(Numero, Nothing) Then
                        For Each c In CamposBusquedaIntegers
                            Expresion &= " or " & c & "=@" & ContNum.ToString
                            ReDim Preserve Parametros(ContNum)
                            Parametros(ContNum) = Integer.Parse(Numero, CultureInfo.InvariantCulture)
                            ContNum += 1
                        Next
                    End If
                Next
            End If

            If CamposBusquedaDoubles IsNot Nothing Then
                For Each palabra In Palabras
                    Dim Numero = palabra.Replace(",", ".")
                    If CamposBusquedaDoubles.Count > 0 AndAlso Double.TryParse(Numero, Nothing) Then
                        For Each c In CamposBusquedaDoubles
                            Expresion &= " or " & c & "=@" & ContNum.ToString
                            ReDim Preserve Parametros(ContNum)
                            Parametros(ContNum) = Double.Parse(Numero, CultureInfo.InvariantCulture)
                            ContNum += 1
                        Next
                    End If
                Next
            End If
            If CamposBusquedaAlfabeticos IsNot Nothing Then
                For Each c In CamposBusquedaAlfabeticos
                    Dim ExpresionParcial As String = ""
                    For Each palabra In Palabras
                        palabra = palabra.Replace(Chr(34), "")
                        ExpresionParcial &= " " & TipoBusqueda & " " & c & ".Contains(" & "@" & ContNum.ToString & ")"
                        ReDim Preserve Parametros(ContNum)
                        Parametros(ContNum) = palabra
                        ContNum += 1
                    Next
                    ExpresionParcial = "(" & ExpresionParcial.Substring(2 + TipoBusqueda.Length) & ")"
                    Expresion &= " or " & ExpresionParcial
                Next
            End If

            If CamposBusquedaAlfabeticosPorIgualdad IsNot Nothing Then
                Dim ExpresionParcial As String = ""
                For Each palabra In Palabras
                    If CamposBusquedaAlfabeticosPorIgualdad.Count > 0 Then
                        For Each c In CamposBusquedaAlfabeticosPorIgualdad
                            ExpresionParcial &= " or " & c & "=" & "@" & ContNum.ToString
                            ReDim Preserve Parametros(ContNum)
                            Parametros(ContNum) = palabra
                            ContNum += 1
                        Next
                    End If
                Next
                ExpresionParcial = "(" & ExpresionParcial.Substring(4) & ")"
                Expresion &= " or " & ExpresionParcial
            End If
            If CamposBusquedaAlfabeticosPorComienzo IsNot Nothing Then
                Dim ExpresionParcial As String = ""
                For Each palabra In Palabras
                    If CamposBusquedaAlfabeticosPorComienzo.Count > 0 Then
                        For Each c In CamposBusquedaAlfabeticosPorComienzo
                            ExpresionParcial &= " " & TipoBusqueda & " " & c & ".StartsWith(" & "@" & ContNum.ToString & ")"
                            ReDim Preserve Parametros(ContNum)
                            Parametros(ContNum) = palabra
                            ContNum += 1
                        Next
                    End If
                Next
                ExpresionParcial = "(" & ExpresionParcial.Substring(1 + TipoBusqueda.Length) & ")"
                Expresion &= " or " & ExpresionParcial
            End If
            If Expresion <> "" Then
                Return Expresion.Substring(4)
            Else
                Return ""
            End If
        End Function

        Public Shared Function IEnumerableAExcelAgrupado(Of t)(Datos As List(Of t)) As Byte()
            Dim ngc As New tsGridControl
            ngc.View = New tsTableView()
            DirectCast(ngc.View, tsTableView).AutoWidth = True
            Dim lc = Datos.GetType.GetProperties.ToList
            For Each oc In lc
                Dim gc As New tsGridColumn()
                gc.FieldName = oc.Name
                gc.Header = oc.Name
                ngc.Columns.Add(gc)
            Next
            ngc.ItemsSource = Datos
            Dim ms As New MemoryStream
            ngc.View.ExportToXlsx(ms)
            ms.Position = 0
            Return ms.ToArray
        End Function
        Public Shared Sub IEnumerableAExcel(Of t)(Datos As IEnumerable(Of t), Fichero As String)
            Dim wb As New ClosedXML.Excel.XLWorkbook
            Dim dt = tsl5.Extensiones.IEnumerableExtensions.CopyToDataTable(Of t)(Datos)
            wb.AddWorksheet(dt)
            wb.SaveAs(Fichero)
        End Sub

        Public Shared Sub IEnumerableAExcel(Of t)(Datos As List(Of t), Fichero As String)
            Dim wb As New ClosedXML.Excel.XLWorkbook
            Dim dt = tsl5.Extensiones.IEnumerableExtensions.CopyToDataTable(Of t)(Datos)
            wb.AddWorksheet(dt)
            wb.SaveAs(Fichero)
        End Sub
        Public Shared Function IEnumerableAExcel(Of t)(Datos As List(Of t)) As Byte()
            Dim wb As New ClosedXML.Excel.XLWorkbook
            Dim dt = tsl5.Extensiones.IEnumerableExtensions.CopyToDataTable(Of t)(Datos)
            wb.AddWorksheet(dt)
            Dim ms As New MemoryStream
            wb.SaveAs(ms)
            ms.Position = 0
            Return ms.ToArray
        End Function
        Public Shared Function ListaIEnumerableAExcel(Of t)(Datos As List(Of List(Of t)), NombreTablas As List(Of String)) As Byte()
            Dim wb As New ClosedXML.Excel.XLWorkbook
            For i = 0 To Datos.Count - 1
                Dim tabla = Datos(i)
                Dim dt = tsl5.Extensiones.IEnumerableExtensions.CopyToDataTable(Of t)(tabla)
                wb.AddWorksheet(dt, NombreTablas(i))
            Next
            Dim ms As New MemoryStream
            wb.SaveAs(ms)
            ms.Position = 0
            Return ms.ToArray
        End Function
    End Class
End Namespace