/// <summary>
        /// Loads user preferences and displays them
        /// </summary>
        private void LoadPreferences()
        {
            DescuentoValue        = UserPreferences.GetDescuento();
            DescuentoInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", DescuentoValue);

            NumeroReciboValue        = UserPreferences.GetNumeroRecibo();
            NumeroReciboInitialValue = NumeroReciboValue;

            UbicacionValue        = UserPreferences.GetPreferredLocation();
            UbicacionInitialValue = UbicacionValue;

            RecibosValue        = UserPreferences.GetRecibosLocation();
            RecibosInitialValue = RecibosValue;

            FacturasValue        = UserPreferences.GetFacturasLocation();
            FacturasInitialValue = FacturasValue;

            ReconexionValue        = UserPreferences.GetReconexionValue();
            ReconexionInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ReconexionValue);

            AfiliacionValue        = UserPreferences.GetAfiliacionValue();
            AfiliacionInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", AfiliacionValue);

            DerivacionValue        = UserPreferences.GetDerivacionValue();
            DerivacionInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", DerivacionValue);

            TrasladoValue        = UserPreferences.GetTrasladoValue();
            TrasladoInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", TrasladoValue);

            TVvalue        = UserPreferences.GetTVValue();
            TVInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", TVvalue);

            Megas3Value        = UserPreferences.Get3MegasValue();
            Megas3InitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", Megas3Value);

            Megas5Value        = UserPreferences.Get5MegasValue();
            Megas5InitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", Megas5Value);

            Megas7Value        = UserPreferences.Get7MegasValue();
            Megas7InitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", Megas7Value);

            Megas10Value        = UserPreferences.Get10MegasValue();
            Megas10InitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", Megas10Value);

            (ComboTV3Value, ComboInternet3Value) = UserPreferences.GetCombo3();
            Combo3TVInitialValue       = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboTV3Value);
            Combo3InternetInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboInternet3Value);

            (ComboTV5Value, ComboInternet5Value) = UserPreferences.GetCombo5();
            Combo5TVInitialValue       = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboTV5Value);
            Combo5InternetInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboInternet5Value);

            (ComboTV7Value, ComboInternet7Value) = UserPreferences.GetCombo7();
            Combo7TVInitialValue       = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboTV7Value);
            Combo7InternetInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboInternet7Value);

            (ComboTV10Value, ComboInternet10Value) = UserPreferences.GetCombo10();
            Combo10TVInitialValue       = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboTV10Value);
            Combo10InternetInitialValue = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", ComboInternet10Value);
        }
        /// <summary>
        /// Generates Recibos de caja.
        /// </summary>
        /// <param name="items">It is a pair of values</param>
        /// <param name="type">The type of recibo de caja</param>
        /// <returns>True if files were generated succesfully</returns>
        public override bool GenerateFiles(List <Tuple <Factura, Customer> > items, string type, object sender, System.Windows.Controls.TextBlock text)
        {
            for (int i = 0; i < items.Count; ++i)
            {
                //Change current operation description
                base.UpdateCurrentOperationDescription("Proceso iniciado  " + (i + 1) + "/" + items.Count);
                text.Dispatcher.Invoke(delegate
                {
                    text.Text = CurrentOperationDescription;
                });
                string concepto = String.Empty;
                int    ct       = 0;
                foreach (Cargo cargo in items.ElementAt(i).Item1.cargos)
                {
                    concepto += cargo.Concepto.ToString().ToUpper();
                    concepto += new StringBuilder(" ").Append(cargo.MesCargado.ToString().ToUpper());

                    if (!(items.ElementAt(i).Item1.cargos.Count - 1 == ct++))
                    {
                        concepto += "-";
                    }
                }


                using (ExcelPackage xlPackage = new ExcelPackage(new System.IO.FileInfo(@UserPreferences.GetRecibosLocation())))
                {
                    //Change current operation description
                    base.UpdateCurrentOperationDescription("Obteniendo directorio");
                    text.Dispatcher.Invoke(delegate
                    {
                        text.Text = CurrentOperationDescription;
                    });

                    StringBuilder DirectoryLocation = new StringBuilder(UserPreferences.GetPreferredLocation()).Append(@"\").Append(type);
                    var           directoryInfo     = System.IO.Directory.CreateDirectory(@DirectoryLocation.ToString());

                    //Change Current Operation Description
                    base.UpdateCurrentOperationDescription("Generando nombres de archivo");
                    text.Dispatcher.Invoke(delegate
                    {
                        text.Text = CurrentOperationDescription;
                    });

                    StringBuilder FileLocationXlsx = new StringBuilder(directoryInfo.FullName).Append(@"\").Append(items.ElementAt(i).Item1.NumeroFactura).Append(FileExtensions.ExcelFormat);
                    StringBuilder FileLocationPDF  = new StringBuilder(directoryInfo.FullName).Append(@"\").Append(items.ElementAt(i).Item1.NumeroFactura).Append(FileExtensions.PDFFormat);

                    try
                    {
                        var worksheet    = xlPackage.Workbook.Worksheets.First();
                        var totalRows    = worksheet.Dimension.End.Row;
                        var totalColumns = worksheet.Dimension.End.Column;

                        //Change Current Operation Description
                        base.UpdateCurrentOperationDescription("Escaneando plantilla");
                        text.Dispatcher.Invoke(delegate
                        {
                            text.Text = CurrentOperationDescription;
                        });

                        int count = 0;
                        for (int rowNum = 1; rowNum <= totalRows; ++rowNum)
                        {
                            for (int colNum = 1; colNum <= totalColumns; ++colNum)
                            {
                                var    row       = worksheet.Cells[rowNum, colNum].Select(c => c.Value == null ? String.Empty : c.Value.ToString());
                                string cellValue = String.Join(",", row);

                                if (cellValue == RecibosKeyWords.NUMERORECIBO)
                                {
                                    int numero_recibo = UserPreferences.GetNumeroRecibo();
                                    worksheet.Cells[rowNum, colNum].Value = new StringBuilder("#").Append(numero_recibo).ToString();
                                    UserPreferences.SaveNumeroRecibo(++numero_recibo);
                                }
                                if (cellValue == RecibosKeyWords.NOMBRES)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = new StringBuilder(items.ElementAt(i).Item2.Nombre).Append(" ").Append(items.ElementAt(i).Item2.Apellido).ToString();
                                }
                                if (cellValue == RecibosKeyWords.FECHA)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = DateManager.GetDateInSpanish();
                                }
                                if (cellValue == RecibosKeyWords.CEDULA)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Cedula;
                                }
                                if (cellValue == RecibosKeyWords.DIRECCION)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Direccion;
                                }
                                if (cellValue == RecibosKeyWords.BARRIO)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Barrio;
                                }
                                if (cellValue == RecibosKeyWords.CONCEPTO)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = concepto;
                                }
                                if (cellValue == RecibosKeyWords.NODO)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Nodo;
                                }
                                if (cellValue == RecibosKeyWords.TELEFONO)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = items.ElementAt(i).Item2.Telefono;
                                }
                                if (cellValue == RecibosKeyWords.MES)
                                {
                                    worksheet.Cells[rowNum, colNum].Value = DateManager.GetMonthInSpanish();
                                }
                                if (cellValue == RecibosKeyWords.VALOR)
                                {
                                    string valorToDisplay = String.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:C}", Valor);
                                    worksheet.Cells[rowNum, colNum].Value = valorToDisplay;
                                }

                                //Change progress value
                                int newProgress = (int)((((float)(++count) / (float)(totalRows * totalColumns)) * (1.0f / (float)items.Count)) * 100);
                                base.UpdateProgreso(newProgress);
                                (sender as BackgroundWorker).ReportProgress(Progress);
                            }
                        }

                        //Change Current Operation Description
                        base.UpdateCurrentOperationDescription("Generando archivo PDF");
                        text.Dispatcher.Invoke(delegate
                        {
                            text.Text = CurrentOperationDescription;
                        });

                        xlPackage.SaveAs(new System.IO.FileInfo(@FileLocationXlsx.ToString()));
                        Workbook workbook = new Application().Workbooks.Open(@FileLocationXlsx.ToString());
                        workbook.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, @FileLocationPDF.ToString());
                        workbook.Close();
                    }
                    catch (Exception)
                    {
                        RollBack(FileLocationXlsx.ToString(), FileLocationPDF.ToString());
                        throw;
                    }
                    finally
                    {
                        File.Delete(@FileLocationXlsx.ToString());
                    }
                }
            }
            base.UpdateProgreso(100);

            (sender as BackgroundWorker).ReportProgress(Progress);
            return(true);
        }
        /// <summary>
        /// Processes the payment
        /// </summary>
        private void Pay()
        {
            if (CedulaCliente is null)
            {
                SystemSounds.Beep.Play();
                MessageBox.Show("Cedula invalida", Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }


            List <Cargo> cargosActualizados = new List <Cargo>();

            foreach (Compra _compra in this.ListViewCompras.Items)
            {
                Cargo cargo = (Cargo)_compra.CargoView;
                cargosActualizados.Add(cargo);
            }
            int pagoTotal = int.Parse(this.TotalText.Content.ToString(), NumberStyles.Currency);

            try
            {
                Factura factura = new Factura();
                //In this case NumeroFactura is used for the name of the file, so its safe not to provide the object with more values
                //Must add number of file to the name of the file to avoid file from being removed if two or more payments happen the same day
                factura.NumeroFactura = new StringBuilder(CedulaCliente).Append("-").Append(DateManager.GetMonthInSpanish()).Append("-").Append(UserPreferences.GetNumeroRecibo()).ToString();
                factura.cargos        = cargosActualizados;
                Customer customer = BDManager.GetCustomer(CedulaCliente);

                if (customer is null)
                {
                    SystemSounds.Beep.Play();
                    MessageBox.Show("Error inesperado", Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }

                RecibosManager                    recibosManager = new RecibosManager();
                Tuple <Factura, Customer>         pair           = new Tuple <Factura, Customer>(factura, customer);
                List <Tuple <Factura, Customer> > info           = new List <Tuple <Factura, Customer> >();
                info.Add(pair);

                try
                {
                    recibosManager.Valor = pagoTotal;
                    LoadingWindow loadingWindow = new LoadingWindow();
                    loadingWindow.Show();
                    loadingWindow.StartWorking((object sender, DoWorkEventArgs e) => {
                        recibosManager.GenerateFiles(info, TypeOfRecibos.PAGO, sender, loadingWindow.Status);

                        this.Dispatcher.Invoke(delegate {
                            loadingWindow.Hide();
                            SystemSounds.Beep.Play();
                            MessageBox.Show("Archivo creado exitosamente", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information);
                        });
                    }
                                               );
                }
                catch (Exception)
                {
                    this.Dispatcher.Invoke(delegate
                    {
                        SystemSounds.Beep.Play();
                        MessageBox.Show(Messages.Errors.CouldntReadFile, Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning);
                    });
                    return;
                }

                try
                {
                    if (descuento == 0)
                    {
                        if (BDManager.Pay(cargosActualizados, CedulaCliente, pagoTotal))
                        {
                            SystemSounds.Beep.Play();
                            MessageBox.Show("Pago exitoso!", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information);
                            Clean();
                        }
                    }
                    else
                    {
                        if (BDManager.Pay(cargosActualizados, CedulaCliente, pagoTotal, descuento, descuentoCargo))
                        {
                            SystemSounds.Beep.Play();
                            MessageBox.Show("Pago exitoso!", Messages.Titles.Success, MessageBoxButton.OK, MessageBoxImage.Information);
                            Clean();
                        }
                    }
                } catch (Exception)
                {
                    SystemSounds.Beep.Play();
                    MessageBox.Show("No se pudo efectuar el pago", Messages.Titles.Warninig, MessageBoxButton.OK, MessageBoxImage.Warning);
                    int resetNumeber = UserPreferences.GetNumeroRecibo();
                    UserPreferences.SaveNumeroRecibo(--resetNumeber);
                }
            } catch (Exception e)
            {
                SystemSounds.Beep.Play();
                MessageBox.Show("Error inesperado. Elimine el archivo generado!" + "\n" + e.Message, Messages.Titles.Alert, MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }