/** Pelayo - 2020
         * Metodo que resetea todos los filtros
         */
        private void ResetAll(Object sender, RoutedEventArgs e)
        {
            //sacamos la columna que se esta filtrando
            int           column       = ((DataGridColumnHeader)((Button)sender).TemplatedParent).Column.DisplayIndex;
            List <Object> columnValues = ((DataView)(this.ItemsSource)).ToTable().AsEnumerable().Select(x => x[column]).Distinct().ToList();

            try
            {
                _workingData.DefaultView.RowFilter = null; //Se asigna al campo la cadena formada
                _workingData.DefaultView.RowFilter = "";   //Se asigna al campo la cadena formada
            }
            catch (EvaluateException)
            {
                WPFForms.ShowError("Error al resetear todos los filtros", "Error en filtrado de todos.");
            }

            for (int i = 0; i < Columns.Count; i++)   //Se recorren las columnas para actualizar la listas de filtros desplegables
            {
                columnValues = ((DataView)(this.ItemsSource)).ToTable().AsEnumerable().Select(x => x[i]).Distinct().ToList();
                List <String> StringValues = columnValues.Select(s => s.ToString()).ToList();

                for (int j = 0; j < FilterHierarchy[i].Filter.Count; j++)
                {
                    if ((StringValues.Contains(FilterHierarchy[i].Filter[j].Name)))
                    {
                        FilterHierarchy[i].Filter[j].IsFilteredInOtherFilter = false;
                        copia[posicion][i].Filter[j].IsFilteredInOtherFilter = false;
                    }
                }
            }
        }
        // Pelayo - 2020
        //Metodo que resetea el filtro desde donde se llama

        private void Reset(Object sender, RoutedEventArgs e)
        {
            //sacamos la columna que se esta filtrando
            int column = ((DataGridColumnHeader)((Button)sender).TemplatedParent).Column.DisplayIndex;
            //sacamos los valores
            List <Object> columnValues = ((DataView)(this.ItemsSource)).ToTable().AsEnumerable().Select(x => x[column]).Distinct().ToList();

            try
            {
                //Aveces funciona uno otras otro, asi que hago los dos
                _workingData.DefaultView.RowFilter = null;   //Se asigna al campo la cadena formada
                _workingData.DefaultView.RowFilter = "";     //Se asigna al campo la cadena formada
            }
            catch (EvaluateException)
            {
                WPFForms.ShowError("Erro al resetear filtros", "No se puede resetear esta columna");
            }

            //se actualizan los filtros solo en la columna que se dio al boton
            //despues de quitar filtros el valor de las columnas cambia (columnValues)
            columnValues = ((DataView)(this.ItemsSource)).ToTable().AsEnumerable().Select(x => x[column]).Distinct().ToList();
            List <String> StringValues = columnValues.Select(s => s.ToString()).ToList();

            for (int j = 0; j < FilterHierarchy[column].Filter.Count; j++)
            {
                if ((StringValues.Contains(FilterHierarchy[column].Filter[j].Name)))
                {
                    FilterHierarchy[column].Filter[j].IsFilteredInOtherFilter = false;
                    copia[posicion][column].Filter[j].IsFilteredInOtherFilter = false;
                }
            }


            //FiltrarColumna(column);
        }
        private void PasteToGrid()
        {
            try
            {
                string      clipBoardText = Clipboard.GetText();
                DataGridRow dgrow         = DataGridRow.GetRowContainingElement(_selectedCell);
                int         x_index       = dgrow.GetIndex();
                DataRowView row           = (DataRowView)dgrow.Item;
                DataView    view          = row.DataView;

                string[] rows = clipBoardText.Split(new[] { "\r\n" }, StringSplitOptions.None);
                for (int i = 0; i < rows.Length; i++)
                {
                    string[] cols = rows[i].Split('\t');
                    for (int j = 0; j < cols.Length; j++)
                    {
                        //cada columna de la tabla puede emplear un tipo de datos distinto, si no coinciden no se pega
                        Type typeOfCell = _workingData.Rows[_workingData.Rows.IndexOf(view[i].Row)][_selectedCell.Column.DisplayIndex + j].GetType();
                        if (typeOfCell == typeof(string))
                        {
                            _workingData.Rows[_workingData.Rows.IndexOf(view[i].Row)][_selectedCell.Column.DisplayIndex + j] = cols[j].Trim();
                        }
                        else if (typeOfCell == typeof(double))
                        {
                            double?aux;
                            if (Conversion.ToDouble(cols[j].Trim(), out aux))
                            {
                                _workingData.Rows[_workingData.Rows.IndexOf(view[i].Row)][_selectedCell.Column.DisplayIndex + j] = aux;
                            }
                        }
                        else if (typeOfCell == typeof(int))
                        {
                            int?aux;
                            if (Conversion.ToInt(cols[j].Trim(), out aux))
                            {
                                _workingData.Rows[_workingData.Rows.IndexOf(view[i].Row)][_selectedCell.Column.DisplayIndex + j] = aux;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                WPFForms.ShowError("No se han podido pegar correctamente los datos", "Puede ser por un tamaño de datos superior al de esta tabla o al uso de un tipo de dato inesperado");
            }
        }
        //tras acabar el procesado en segundo plano se actualiza la interfaz con ellos
        private void BackGround_Completed(object sender, RunWorkerCompletedEventArgs e)
        {
            // Progress_Bar.Value = 100;
            if (e.Error == null)
            {
                //Paramos de girar el cursor
                Cursor = Cursors.Arrow;

                plotNodo.Visibility   = Visibility;
                plotceldas.Visibility = Visibility;


                bgwBlnOffResult output = (bgwBlnOffResult)e.Result;
                Copiaoutput = output;
                if (output.colindancias != null)
                {
                    colinGrid.WorkingData = output.colindancias;
                    WPFForms.FindParent <TabItem>(colinGrid).Visibility = Visibility.Visible;
                    tabColindancias.IsSelected = true;



                    //fc = new formColindancias(output.colindancias);

                    //fc.Show();
                }

                if (output.siteCoordErrors != "" && (bool)Is_BlnOFF_Enabled.IsChecked)
                {
                    WPFForms.ShowError("Faltan las coordenadas de los siguientes emplazamientos", output.siteCoordErrors);
                }

                if (output.candBl != null)
                {
                    candBLGrid.WorkingData = output.candBl;
                    WPFForms.FindParent <TabItem>(candBLGrid).Visibility = Visibility.Visible;
                }
                if (output.candOff != null)
                {
                    candOFFGrid.WorkingData = output.candOff;
                    WPFForms.FindParent <TabItem>(candOFFGrid).Visibility = Visibility.Visible;
                }
                if (output.error != null)
                {   //se genera la tabla de analis previo
                    errGrid.WorkingData = output.error;
                    WPFForms.FindParent <TabItem>(errGrid).Visibility = Visibility.Visible;

                    //se genera la gárafica por nodos
                    this.erroresAMejorar = output.error;

                    List <string> sites = erroresAMejorar.AsEnumerable().Select(col => (string)col[1]).Distinct().ToList();
                    siteListBox_1.ItemsSource  = sites;
                    siteListBox_1.SelectedItem = sites[0];

                    List <string> Tech = this.erroresAMejorar.AsEnumerable().Where(row => (string)row[1] == (string)siteListBox_1.SelectedItem).Select(col => (string)col[2]).Distinct().ToList <string>();
                    techListBox_1.ItemsSource  = Tech;
                    techListBox_1.SelectedItem = Tech[0];

                    UpdateGraph_1();
                }
                if (output.nirPlotData != null)
                {
                    this.nirPlotData = output.nirPlotData;

                    List <string> sites = erroresAMejorar.AsEnumerable().Select(col => (string)col[1]).Distinct().ToList();
                    siteListBox_2.ItemsSource  = sites;
                    siteListBox_2.SelectedItem = sites[0];

                    List <string> tech = this.nirPlotData.AsEnumerable().Where(row => (string)row[1] == (string)siteListBox_2.SelectedItem).Select(col => (string)col[3]).Distinct().ToList <string>();
                    techListBox_2.ItemsSource  = tech;
                    techListBox_2.SelectedItem = tech[0];

                    var cells2Plot = nirPlotData.AsEnumerable()
                                     .Where(row => (string)row[1] == (string)siteListBox_2.SelectedItem && (string)row[3] == (string)techListBox_2.SelectedItem)
                                     .Select(col => (string)col[2]).Distinct().Where(item => !item.Contains("="));

                    List <SectorListItem> sectors = new List <SectorListItem>();
                    foreach (var cell in cells2Plot)
                    {
                        sectors.Add(new SectorListItem()
                        {
                            Enabled = true, Sector = TECH_NUM.GetSectorFromLNCEL(cell)
                        });
                    }
                    this.Sectors = sectors;

                    Binding codeBinding = new Binding("Sectors");
                    codeBinding.Source = this;
                    sectorListBox.SetBinding(ListBox.ItemsSourceProperty, codeBinding);

                    UpdateGraph_2();
                }
            }
            else
            {
                //Paramos de girar el cursor
                Cursor = Cursors.Arrow;

                //control de errores en BackGround
                switch (e.Error.GetType().Name)
                {
                case "FileNotFoundException":
                    WPFForms.ShowError("Falta un archivo", e.Error.Message);
                    break;

                case "InvalidOperationException":
                    WPFForms.ShowError("Error critico", e.Error.Message);
                    break;

                case "ArgumentException":
                    WPFForms.ShowError("Error en los datos", e.Error.Message);
                    break;

                default:
                    WPFForms.ShowError("No controlado", e.Error.Message);
                    break;
                }
            }
        }
        private void Launch(object sender, RoutedEventArgs e)
        {
            //Ocultamos las demas pestañas
            tabColindancias.Visibility  = Visibility.Collapsed;
            tabCandidatasBL.Visibility  = Visibility.Collapsed;
            tabCandidatasOFF.Visibility = Visibility.Collapsed;
            tabErrores.Visibility       = Visibility.Collapsed;
            plotNodo.Visibility         = Visibility.Collapsed;
            plotceldas.Visibility       = Visibility.Collapsed;

            //Empieza a girar el cursor
            Cursor = Cursors.Wait;

            //   Progress_Bar.Value = Progress_Bar.Minimum;



            String[] aux = new String[lnBtsInputGrid.Count];
            int      n   = 0;

            for (int i = 0; i < lnBtsInputGrid.Count; i++)
            {
                if (lnBtsInputGrid[i].LnBtsName != "")
                {
                    aux[i] = lnBtsInputGrid[i].LnBtsName;
                    n++;
                }
            }
            string[] lnBtsInputs = new string[n];
            for (int i = 0; i < n; i++)
            {
                lnBtsInputs[i] = aux[i];
            }
            aux = null;

            if (lnBtsInputs.Length == 0)
            {
                WPFForms.ShowError("No hay nodos de entrada", "Rellena la tabla de INPUT SITES");
                return;
            }
            //se preparan los inputs para pasarlos como argumento al background worker
            bgwBlnOffArgument args = new bgwBlnOffArgument();

            args.lnBtsInputs         = lnBtsInputs;
            args.pathR31             = RSLTE31_path.Text;
            args.pathTA              = TA_path.Text;
            args.pathSRAN            = SRAN_path.Text;
            args.pathFL18            = FL18_path.Text;
            args.pathNIR48           = NIR_path.Text;
            args.BLnOffEnabled       = (bool)Is_BlnOFF_Enabled.IsChecked;
            args.prevAnalisysEnabled = (bool)Is_PrevAnalysis_Enabled.IsChecked;
            args.pathSRAN2           = SRAN2_path.Text;


            if (estaSranDividido.IsChecked == true)
            {
                args.srandividio = true;
            }
            else
            {
                args.srandividio = false;
            }

            if (conFL18.IsChecked == true)
            {
                args.conFL18 = true;
            }
            else
            {
                args.conFL18 = false;
            }


            if (cbRellenarLabels.IsChecked == true)
            {
                args.rellenarLabel = true;
            }
            else
            {
                args.rellenarLabel = false;
            }



            worker.WorkerReportsProgress = true;
            worker.DoWork             += BackGround_Work;
            worker.ProgressChanged    += BackGround_Progress;
            worker.RunWorkerCompleted += BackGround_Completed;
            worker.RunWorkerAsync(args);

            //Task<ProgressDialogController> progressBar = WPFForms.ShowProgress("Ejecutando BlackListing y Offset","Procesando consulta 31");

            //Guardar el path de los ultimos archivos en un fichero de texto
            string[] storePaths = new string[6] {
                RSLTE31_path.Text, TA_path.Text, SRAN_path.Text, FL18_path.Text, NIR_path.Text, SRAN2_path.Text
            };
            System.IO.File.WriteAllLines(Path.Combine(Environment.CurrentDirectory, @"BlnOFF\Data\", "RememberPaths.txt"), storePaths);
        }
        /** Pelayo - 2020
         * Metodo que filtra una unica columna
         */

        private void FiltrarColumna(int col)
        {
            if (_workingData.DefaultView.RowFilter == "")
            {
                isFiltered = false;
            }
            int           column       = col;
            List <Object> columnValues = ((DataView)(this.ItemsSource)).ToTable().AsEnumerable().Select(x => x[column]).Distinct().ToList();
            var           aux          = FilterHierarchy[column].Filter.Where(x => (x.NotFiltered == true) && (x.IsTextFiltered == false) && (x.IsFilteredInOtherFilter == false)).Distinct().ToList(); // Se obtiene la lista de elementos de la columna con el checkbox marcado
            string        filtro       = _workingData.DefaultView.RowFilter;                                                                                                                            // Se coge el filtro anterior si lo hubiera.

            if (aux.Count == 0 || aux.Count == columnValues.Count)
            {
                return;          //Si no se ha marcado ninguna checkbox el método no hace nada
            }
            if (aux.Count == 1)  //Es necesario diferenciar si solo se ha marcado un elemento
            {
                if (!isFiltered) //También se comprueba si ya se había filtrado anteriormente
                {
                    filtro += " ([" + _workingData.Columns[column].ColumnName + "] IN ('" + aux[0].Name + "' ))";
                }
                else
                {
                    filtro += "AND ([" + _workingData.Columns[column].ColumnName + "] IN ('" + aux[0].Name + "' )) ";
                }
            }
            else
            {
                if (!isFiltered)
                {
                    filtro += "( [" + _workingData.Columns[column].ColumnName + "]  IN ( '" + aux[0].Name + "' , ";
                    for (int i = 1; i < aux.Count - 1; i++)
                    {
                        filtro = filtro + "'" + aux[i].Name + "' , ";
                    }
                }

                else
                {
                    filtro += " AND ( [" + _workingData.Columns[column].ColumnName + "] IN ( '" + aux[0].Name + "' , ";
                    for (int i = 1; i < aux.Count - 1; i++)
                    {
                        filtro = filtro + "'" + aux[i].Name + "' , ";
                    }
                }
                filtro = filtro + "'" + aux[aux.Count - 1].Name + "' ))";
            }
            if (filtro != _workingData.DefaultView.RowFilter)
            {
                posicion++;
                activeFilters++;
                filtros[posicion] = filtro;
                isFiltered        = true;
                try
                {
                    _workingData.DefaultView.RowFilter = filtro; //Se asigna al campo la cadena formada
                    //_workingData.DefaultView.RowFilter = ""; //test para quitar filtros
                }
                catch (EvaluateException)
                {
                    WPFForms.ShowError("Has intentado filtrar una columna de valores numéricos dejando el valor vacío.", "Desmarca el valor vacío.");
                    Undo_Filter();
                }
            }

            for (int i = 0; i < Columns.Count; i++)   //Se recorren las columnas para actualizar la listas de filtros desplegables
            {
                columnValues = ((DataView)(this.ItemsSource)).ToTable().AsEnumerable().Select(x => x[i]).Distinct().ToList();
                List <String> StringValues = columnValues.Select(s => s.ToString()).ToList();

                for (int j = 0; j < FilterHierarchy[i].Filter.Count; j++)
                {
                    if (!(StringValues.Contains(FilterHierarchy[i].Filter[j].Name)))
                    {
                        FilterHierarchy[i].Filter[j].IsFilteredInOtherFilter = true;
                        copia[posicion][i].Filter[j].IsFilteredInOtherFilter = true;
                    }
                }
            }
        }