using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Configuration;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace DescargaMasiva
{
	public class FrmDownloadXml : Form
	{
		private string _currentUrl;

		private readonly bool _supplierStructure;

		private readonly WebBrowser _wbSat;

		private IContainer components = null;

		private TextBox txtPassword;

		private StatusStrip statusStrip1;

		private Label label1;

		private Label label2;

		private Label label3;

		private Label label4;

		private Label label5;

		private Label label7;

		private Label lblDownloadPath;

		private GroupBox groupBox2;

		private RadioButton rbtMonth;

		private RadioButton rbtDay;

		private GroupBox groupBox3;

		private Panel panel1;

		private RadioButton rbtReceived;

		private RadioButton rbtSended;

		private GroupBox groupBox4;

		private Button btnBrowse;

		private Button btnDownload;

		private Label label8;

		private Label label6;

		private ComboBox cmbYear;

		private ComboBox cmbEnd;

		private ComboBox cmbInitial;

		private TextBox txtLog;

		private Label lblStatus;

		private MenuStrip menuStrip1;

		private ToolStripMenuItem configuraciónToolStripMenuItem;

		private ToolStripMenuItem licenciaToolStripMenuItem;

		private ComboBox cmbAccount;

		public FrmDownloadXml()
		{
			this.InitializeComponent();
			this._wbSat = new WebBrowser();
			this._wbSat.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(this.wbSAT_DocumentCompleted);
			this._supplierStructure = bool.Parse(ConfigurationManager.AppSettings["SupplierStructure"]);
			this.lblDownloadPath.Text = ConfigurationManager.AppSettings["DownloadPath"];
			this.InitControls();
		}

		private void Authenticate()
		{
			try
			{
				Uri uri = new Uri(string.Format("https://cfdiau.sat.gob.mx/nidp/app/login?id=SATUPCFDiCon&sid=0&option=credential&sid=0&Ecom_User_ID={0}&Ecom_Password={1}", this.cmbAccount.SelectedItem, this.txtPassword.Text.Trim()));
				this.Message(string.Format("Iniciando sesion del usuario {0}.", this.cmbAccount.SelectedItem));
				this._wbSat.Navigate(uri);
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void btnBrowse_Click(object sender, EventArgs e)
		{
			try
			{
				FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
				folderBrowserDialog.SelectedPath = this.lblDownloadPath.Text;
				FolderBrowserDialog folderBrowserDialog1 = folderBrowserDialog;
				folderBrowserDialog1.ShowDialog();
				this.lblDownloadPath.Text = folderBrowserDialog1.SelectedPath;
				this.lblStatus.Text = "";
			}
			catch (Exception exception)
			{
				this.lblStatus.Text = exception.Message;
			}
		}

		private void button1_Click(object sender, EventArgs e)
		{
			try
			{
				if (!Internet.IsConnectedToInternet())
				{
					this.Message("Se requiere conexión a Internet para utilizar esta aplicación.");
					return;
				}
				else if (!(this.txtPassword.Text.Trim() == ""))
				{
					this.Authenticate();
				}
				else
				{
					this.txtPassword.Focus();
					this.Message("Debe de proporcionar la contraseña CIEC.");
					return;
				}
			}
			catch (Exception exception)
			{
				this.Message(exception.Message);
			}
		}

		private void cmbYear_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.cmbInitial.SelectedIndex = 0;
			if (int.Parse(this.cmbYear.SelectedItem.ToString()) == DateTime.Now.Year)
			{
				ComboBox month = this.cmbEnd;
				DateTime now = DateTime.Now;
				month.SelectedIndex = now.Month - 1;
			}
			else
			{
				this.cmbEnd.SelectedIndex = 11;
			}
		}

		protected override void Dispose(bool disposing)
		{
			bool flag;
			flag = (!disposing ? true : this.components == null);
			if (!flag)
			{
				this.components.Dispose();
			}
			base.Dispose(disposing);
		}

		private void DownloadFile(string address, string fileName)
		{
			try
			{
				string cookie = CookieReader.GetCookie(this._wbSat.Url.ToString());
				WebClient webClient = new WebClient();
				if (File.Exists(fileName))
				{
					this.Message(string.Format("El archivo {0} ya existe.\n", fileName));
				}
				else
				{
					webClient.Headers.Add(HttpRequestHeader.Cookie, cookie);
					webClient.DownloadFile(address, fileName);
					this.Message(string.Format("Creando el archivo {0}.\n", fileName));
				}
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private static IEnumerable<HtmlElement> ElementsByClass(HtmlDocument doc, string className)
		{
			IEnumerable<HtmlElement> htmlElements = doc.All.Cast<HtmlElement>().Where<HtmlElement>((HtmlElement e) => {
				bool attribute = e.GetAttribute("className") == className;
				return attribute;
			});
			return htmlElements;
		}

		private void FillCombos()
		{
			try
			{
				this.cmbYear.Items.Clear();
				for (int i = DateTime.Now.Year; i >= 2011; i--)
				{
					this.cmbYear.Items.Add(i);
				}
				this.cmbYear.SelectedIndex = 0;
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void FinishSession()
		{
			try
			{
				this.Message(string.Format("Cerrar sesion usuario {0}.", this.cmbAccount.SelectedItem));
				this._wbSat.Navigate(new Uri("https://portalcfdi.facturaelectronica.sat.gob.mx/logout.aspx?salir=y"));
				this.Message("Proceso terminado.");
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void GetReceivedDocuments(int year, int month, int day)
		{
			bool flag;
			bool flag1;
			bool flag2;
			try
			{
				if (this._wbSat.Document != null)
				{
					HtmlElement elementById = this._wbSat.Document.GetElementById("ctl00_MainContent_RdoFechas");
					if (elementById != null)
					{
						elementById.InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement htmlElement = this._wbSat.Document.GetElementById("DdlAnio");
						flag1 = (htmlElement == null ? true : !(htmlElement.GetAttribute("disabled") != "disabled"));
						if (!flag1)
						{
							break;
						}
					}
					HtmlElement elementById1 = this._wbSat.Document.GetElementById("DdlAnio");
					if (elementById1 != null)
					{
						elementById1.SetAttribute("value", year.ToString(CultureInfo.InvariantCulture));
					}
					HtmlElement htmlElement1 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFecha_DdlMes");
					if (htmlElement1 != null)
					{
						htmlElement1.SetAttribute("value", month.ToString("0"));
					}
					HtmlElement elementById2 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFecha_DdlDia");
					if (elementById2 != null)
					{
						elementById2.SetAttribute("value", day.ToString("00"));
					}
					HtmlElement htmlElement2 = this._wbSat.Document.GetElementById("ctl00_MainContent_BtnBusqueda");
					if (htmlElement2 != null)
					{
						htmlElement2.InvokeMember("click");
					}
					int num = 0;
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement elementById3 = this._wbSat.Document.GetElementById("ctl00_MainContent_UpdateProgress1");
						if (!(elementById3 == null))
						{
							flag2 = (elementById3.Style != "display: none;" ? true : num <= 100000);
							if (!flag2)
							{
								break;
							}
							num++;
						}
					}
					this.ProcessResult();
				}
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void GetReceivedDocuments(int year, int month)
		{
			bool flag;
			bool flag1;
			bool flag2;
			try
			{
				if (this._wbSat.Document != null)
				{
					HtmlElement elementById = this._wbSat.Document.GetElementById("ctl00_MainContent_RdoFechas");
					if (elementById != null)
					{
						elementById.InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement htmlElement = this._wbSat.Document.GetElementById("DdlAnio");
						flag1 = (htmlElement == null ? true : !(htmlElement.GetAttribute("disabled") != "disabled"));
						if (!flag1)
						{
							break;
						}
					}
					HtmlElement elementById1 = this._wbSat.Document.GetElementById("DdlAnio");
					if (elementById1 != null)
					{
						elementById1.SetAttribute("value", year.ToString(CultureInfo.InvariantCulture));
					}
					HtmlElement htmlElement1 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFecha_DdlMes");
					if (htmlElement1 != null)
					{
						htmlElement1.SetAttribute("value", month.ToString("0"));
					}
					HtmlElement elementById2 = this._wbSat.Document.GetElementById("ctl00_MainContent_BtnBusqueda");
					if (elementById2 != null)
					{
						elementById2.InvokeMember("click");
					}
					int num = 0;
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement htmlElement2 = this._wbSat.Document.GetElementById("ctl00_MainContent_UpdateProgress1");
						if (!(htmlElement2 == null))
						{
							flag2 = (htmlElement2.Style != "display: none;" ? true : num <= 100000);
							if (!flag2)
							{
								break;
							}
							num++;
						}
					}
					if (this._wbSat.Document.GetElementById("ctl00_MainContent_PnlLimiteRegistros") != null)
					{
						MessageBox.Show("La consulta realizada solo muestra los primeros 500 registros, se recomienda hacer la descarga por día", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					}
					this.ProcessResult();
				}
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void GetSendedDocuments(int year, int month, int day)
		{
			HtmlElement elementById;
			bool flag;
			bool flag1;
			bool flag2;
			bool flag3;
			bool flag4;
			try
			{
				if (this._wbSat.Document != null)
				{
					HtmlElement htmlElement = this._wbSat.Document.GetElementById("ctl00_MainContent_RdoFechas");
					if (htmlElement != null)
					{
						htmlElement.InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement elementById1 = this._wbSat.Document.GetElementById("ctl00_MainContent_TxtRfcReceptor");
						flag1 = (elementById1 == null ? true : !(elementById1.GetAttribute("disabled") != "disabled"));
						if (!flag1)
						{
							break;
						}
					}
					DateTime dateTime = new DateTime(year, month, day);
					HtmlElement htmlElement1 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFechaInicial2_Calendario_text");
					if (htmlElement1 != null)
					{
						htmlElement1.SetAttribute("value", dateTime.ToString("dd/MM/yyyy"));
					}
					HtmlElement elementById2 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFechaInicial2_BtnFecha2");
					if (elementById2 != null)
					{
						elementById2.InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						elementById = this._wbSat.Document.GetElementById("datepicker");
						flag2 = (elementById == null ? true : !elementById.Style.Contains("visibility: visible"));
						if (!flag2)
						{
							break;
						}
					}
					IEnumerable<HtmlElement> htmlElements = FrmDownloadXml.ElementsByClass(this._wbSat.Document, "dpDayHighlightTD");
					if (htmlElements != null)
					{
						htmlElements.First<HtmlElement>().InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						elementById = this._wbSat.Document.GetElementById("datepicker");
						flag3 = (elementById == null ? true : elementById.Style.Contains("visibility: visible"));
						if (!flag3)
						{
							break;
						}
					}
					HtmlElement htmlElement2 = this._wbSat.Document.GetElementById("ctl00_MainContent_BtnBusqueda");
					if (htmlElement2 != null)
					{
						htmlElement2.InvokeMember("click");
					}
					int num = 0;
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement elementById3 = this._wbSat.Document.GetElementById("ctl00_MainContent_UpdateProgress1");
						if (!(elementById3 == null))
						{
							flag4 = (elementById3.Style != "display: none;" ? true : num <= 100000);
							if (!flag4)
							{
								break;
							}
							num++;
						}
					}
					this.ProcessResult();
				}
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void GetSendedDocuments(int year, int month)
		{
			HtmlElement elementById;
			bool flag;
			DateTime dateTime;
			bool flag1;
			bool flag2;
			bool flag3;
			bool flag4;
			bool flag5;
			bool flag6;
			try
			{
				if (this._wbSat.Document != null)
				{
					HtmlElement htmlElement = this._wbSat.Document.GetElementById("ctl00_MainContent_RdoFechas");
					if (htmlElement != null)
					{
						htmlElement.InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement elementById1 = this._wbSat.Document.GetElementById("ctl00_MainContent_TxtRfcReceptor");
						flag1 = (elementById1 == null ? true : !(elementById1.GetAttribute("disabled") != "disabled"));
						if (!flag1)
						{
							break;
						}
					}
					HtmlElement htmlElement1 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFechaInicial2_Calendario_text");
					if (htmlElement1 != null)
					{
						dateTime = new DateTime(year, month, 1);
						htmlElement1.SetAttribute("value", dateTime.ToString("dd/MM/yyyy"));
					}
					HtmlElement elementById2 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFechaInicial2_BtnFecha2");
					if (elementById2 != null)
					{
						elementById2.InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						elementById = this._wbSat.Document.GetElementById("datepicker");
						flag2 = (elementById == null ? true : !elementById.Style.Contains("visibility: visible"));
						if (!flag2)
						{
							break;
						}
					}
					IEnumerable<HtmlElement> htmlElements = FrmDownloadXml.ElementsByClass(this._wbSat.Document, "dpDayHighlightTD");
					if (htmlElements != null)
					{
						htmlElements.First<HtmlElement>().InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						elementById = this._wbSat.Document.GetElementById("datepicker");
						flag3 = (elementById == null ? true : elementById.Style.Contains("visibility: visible"));
						if (!flag3)
						{
							break;
						}
					}
					HtmlElement htmlElement2 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFechaFinal2_Calendario_text");
					if (htmlElement2 != null)
					{
						dateTime = new DateTime(year, month, DateTime.DaysInMonth(year, month));
						htmlElement2.SetAttribute("value", dateTime.ToString("dd/MM/yyyy"));
					}
					HtmlElement elementById3 = this._wbSat.Document.GetElementById("ctl00_MainContent_CldFechaFinal2_BtnFecha2");
					if (elementById3 != null)
					{
						elementById3.InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						elementById = this._wbSat.Document.GetElementById("datepicker");
						flag4 = (elementById == null ? true : !elementById.Style.Contains("visibility: visible"));
						if (!flag4)
						{
							break;
						}
					}
					htmlElements = FrmDownloadXml.ElementsByClass(this._wbSat.Document, "dpDayHighlightTD");
					if (htmlElements != null)
					{
						htmlElements.First<HtmlElement>().InvokeMember("click");
					}
					while (true)
					{
						flag = true;
						Application.DoEvents();
						elementById = this._wbSat.Document.GetElementById("datepicker");
						flag5 = (elementById == null ? true : elementById.Style.Contains("visibility: visible"));
						if (!flag5)
						{
							break;
						}
					}
					HtmlElement htmlElement3 = this._wbSat.Document.GetElementById("ctl00_MainContent_BtnBusqueda");
					if (htmlElement3 != null)
					{
						htmlElement3.InvokeMember("click");
					}
					int num = 0;
					while (true)
					{
						flag = true;
						Application.DoEvents();
						HtmlElement elementById4 = this._wbSat.Document.GetElementById("ctl00_MainContent_UpdateProgress1");
						if (!(elementById4 == null))
						{
							flag6 = (elementById4.Style != "display: none;" ? true : num <= 100000);
							if (!flag6)
							{
								break;
							}
							num++;
						}
					}
					if (this._wbSat.Document.GetElementById("ctl00_MainContent_PnlLimiteRegistros") != null)
					{
						MessageBox.Show("La consulta realizada solo muestra los primeros 500 registros, se recomienda hacer la descarga por día", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
					}
					this.ProcessResult();
				}
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void InitControls()
		{
			try
			{
				this.FillCombos();
				this.lblStatus.Text = "";
				this.cmbAccount.Items.Clear();
				foreach (string keyAccount in (new FrmAddAccount()).GetKeyAccounts())
				{
					this.cmbAccount.Items.Add(keyAccount);
				}
				if (this.cmbAccount.Items.Count > 0)
				{
					this.cmbAccount.SelectedIndex = 0;
				}
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void InitializeComponent()
		{
			this.txtPassword = new TextBox();
			this.statusStrip1 = new StatusStrip();
			this.label1 = new Label();
			this.label2 = new Label();
			this.label3 = new Label();
			this.label4 = new Label();
			this.label5 = new Label();
			this.label7 = new Label();
			this.lblDownloadPath = new Label();
			this.groupBox2 = new GroupBox();
			this.btnBrowse = new Button();
			this.btnDownload = new Button();
			this.label8 = new Label();
			this.rbtMonth = new RadioButton();
			this.rbtDay = new RadioButton();
			this.groupBox3 = new GroupBox();
			this.cmbEnd = new ComboBox();
			this.cmbInitial = new ComboBox();
			this.cmbYear = new ComboBox();
			this.label6 = new Label();
			this.panel1 = new Panel();
			this.rbtReceived = new RadioButton();
			this.rbtSended = new RadioButton();
			this.groupBox4 = new GroupBox();
			this.cmbAccount = new ComboBox();
			this.txtLog = new TextBox();
			this.lblStatus = new Label();
			this.menuStrip1 = new MenuStrip();
			this.configuraciónToolStripMenuItem = new ToolStripMenuItem();
			this.licenciaToolStripMenuItem = new ToolStripMenuItem();
			this.groupBox2.SuspendLayout();
			this.groupBox3.SuspendLayout();
			this.panel1.SuspendLayout();
			this.groupBox4.SuspendLayout();
			this.menuStrip1.SuspendLayout();
			base.SuspendLayout();
			this.txtPassword.Location = new Point(74, 46);
			this.txtPassword.Name = "txtPassword";
			this.txtPassword.PasswordChar = '*';
			this.txtPassword.Size = new System.Drawing.Size(112, 20);
			this.txtPassword.TabIndex = 3;
			this.txtPassword.Enter += new EventHandler(this.txtPassword_Enter);
			this.statusStrip1.Location = new Point(0, 389);
			this.statusStrip1.Name = "statusStrip1";
			this.statusStrip1.Size = new System.Drawing.Size(884, 22);
			this.statusStrip1.TabIndex = 6;
			this.statusStrip1.Text = "statusStrip1";
			this.label1.AutoSize = true;
			this.label1.Location = new Point(6, 22);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(31, 13);
			this.label1.TabIndex = 0;
			this.label1.Text = "RFC:";
			this.label2.AutoSize = true;
			this.label2.Location = new Point(6, 48);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(64, 13);
			this.label2.TabIndex = 2;
			this.label2.Text = "Contraseña:";
			this.label3.AutoSize = true;
			this.label3.Location = new Point(6, 48);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(50, 13);
			this.label3.TabIndex = 2;
			this.label3.Text = "Ejercicio:";
			this.label4.AutoSize = true;
			this.label4.Location = new Point(6, 74);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(40, 13);
			this.label4.TabIndex = 4;
			this.label4.Text = "Perido:";
			this.label5.AutoSize = true;
			this.label5.Location = new Point(156, 74);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(15, 13);
			this.label5.TabIndex = 6;
			this.label5.Text = "al";
			this.label7.AutoSize = true;
			this.label7.Location = new Point(6, 48);
			this.label7.Name = "label7";
			this.label7.Size = new System.Drawing.Size(58, 13);
			this.label7.TabIndex = 3;
			this.label7.Text = "Ubicación:";
			this.lblDownloadPath.AutoSize = true;
			this.lblDownloadPath.Location = new Point(70, 48);
			this.lblDownloadPath.Name = "lblDownloadPath";
			this.lblDownloadPath.Size = new System.Drawing.Size(87, 13);
			this.lblDownloadPath.TabIndex = 4;
			this.lblDownloadPath.Text = "lblDownloadPath";
			this.groupBox2.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
			this.groupBox2.Controls.Add(this.btnBrowse);
			this.groupBox2.Controls.Add(this.btnDownload);
			this.groupBox2.Controls.Add(this.label8);
			this.groupBox2.Controls.Add(this.rbtMonth);
			this.groupBox2.Controls.Add(this.rbtDay);
			this.groupBox2.Controls.Add(this.label7);
			this.groupBox2.Controls.Add(this.lblDownloadPath);
			this.groupBox2.Location = new Point(513, 27);
			this.groupBox2.Name = "groupBox2";
			this.groupBox2.Size = new System.Drawing.Size(359, 105);
			this.groupBox2.TabIndex = 2;
			this.groupBox2.TabStop = false;
			this.groupBox2.Text = "Descarga";
			this.btnBrowse.Anchor = AnchorStyles.Top | AnchorStyles.Right;
			this.btnBrowse.Location = new Point(9, 69);
			this.btnBrowse.Name = "btnBrowse";
			this.btnBrowse.Size = new System.Drawing.Size(31, 23);
			this.btnBrowse.TabIndex = 5;
			this.btnBrowse.Text = "...";
			this.btnBrowse.UseVisualStyleBackColor = true;
			this.btnBrowse.Click += new EventHandler(this.btnBrowse_Click);
			this.btnDownload.Anchor = AnchorStyles.Top | AnchorStyles.Right;
			this.btnDownload.Location = new Point(278, 70);
			this.btnDownload.Name = "btnDownload";
			this.btnDownload.Size = new System.Drawing.Size(75, 23);
			this.btnDownload.TabIndex = 5;
			this.btnDownload.Text = "&Descargar";
			this.btnDownload.UseVisualStyleBackColor = true;
			this.btnDownload.Click += new EventHandler(this.button1_Click);
			this.label8.AutoSize = true;
			this.label8.Location = new Point(6, 22);
			this.label8.Name = "label8";
			this.label8.Size = new System.Drawing.Size(31, 13);
			this.label8.TabIndex = 0;
			this.label8.Text = "Tipo:";
			this.rbtMonth.AutoSize = true;
			this.rbtMonth.Checked = true;
			this.rbtMonth.Location = new Point(131, 18);
			this.rbtMonth.Name = "rbtMonth";
			this.rbtMonth.Size = new System.Drawing.Size(65, 17);
			this.rbtMonth.TabIndex = 2;
			this.rbtMonth.TabStop = true;
			this.rbtMonth.Text = "Mensual";
			this.rbtMonth.UseVisualStyleBackColor = true;
			this.rbtDay.AutoSize = true;
			this.rbtDay.Location = new Point(73, 18);
			this.rbtDay.Name = "rbtDay";
			this.rbtDay.Size = new System.Drawing.Size(52, 17);
			this.rbtDay.TabIndex = 1;
			this.rbtDay.Text = "Diaria";
			this.rbtDay.UseVisualStyleBackColor = true;
			this.groupBox3.Controls.Add(this.cmbEnd);
			this.groupBox3.Controls.Add(this.cmbInitial);
			this.groupBox3.Controls.Add(this.cmbYear);
			this.groupBox3.Controls.Add(this.label6);
			this.groupBox3.Controls.Add(this.panel1);
			this.groupBox3.Controls.Add(this.label3);
			this.groupBox3.Controls.Add(this.label4);
			this.groupBox3.Controls.Add(this.label5);
			this.groupBox3.Location = new Point(217, 27);
			this.groupBox3.Name = "groupBox3";
			this.groupBox3.Size = new System.Drawing.Size(290, 105);
			this.groupBox3.TabIndex = 1;
			this.groupBox3.TabStop = false;
			this.groupBox3.Text = "Busqueda";
			this.cmbEnd.DropDownStyle = ComboBoxStyle.DropDownList;
			this.cmbEnd.FormattingEnabled = true;
			ComboBox.ObjectCollection items = this.cmbEnd.Items;
			object[] objArray1 = new object[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
			items.AddRange(objArray1);
			this.cmbEnd.Location = new Point(177, 70);
			this.cmbEnd.Name = "cmbEnd";
			this.cmbEnd.Size = new System.Drawing.Size(36, 21);
			this.cmbEnd.TabIndex = 10;
			this.cmbInitial.DropDownStyle = ComboBoxStyle.DropDownList;
			this.cmbInitial.FormattingEnabled = true;
			ComboBox.ObjectCollection objectCollections = this.cmbInitial.Items;
			objArray1 = new object[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" };
			objectCollections.AddRange(objArray1);
			this.cmbInitial.Location = new Point(114, 70);
			this.cmbInitial.Name = "cmbInitial";
			this.cmbInitial.Size = new System.Drawing.Size(36, 21);
			this.cmbInitial.TabIndex = 9;
			this.cmbYear.DropDownStyle = ComboBoxStyle.DropDownList;
			this.cmbYear.FormattingEnabled = true;
			this.cmbYear.Location = new Point(114, 43);
			this.cmbYear.Name = "cmbYear";
			this.cmbYear.Size = new System.Drawing.Size(52, 21);
			this.cmbYear.TabIndex = 8;
			this.cmbYear.SelectedIndexChanged += new EventHandler(this.cmbYear_SelectedIndexChanged);
			this.label6.AutoSize = true;
			this.label6.Location = new Point(6, 22);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(102, 13);
			this.label6.TabIndex = 0;
			this.label6.Text = "Tipo de documento:";
			this.panel1.Controls.Add(this.rbtReceived);
			this.panel1.Controls.Add(this.rbtSended);
			this.panel1.Location = new Point(114, 19);
			this.panel1.Name = "panel1";
			this.panel1.Size = new System.Drawing.Size(150, 20);
			this.panel1.TabIndex = 1;
			this.rbtReceived.AutoSize = true;
			this.rbtReceived.Checked = true;
			this.rbtReceived.Location = new Point(73, 1);
			this.rbtReceived.Name = "rbtReceived";
			this.rbtReceived.Size = new System.Drawing.Size(72, 17);
			this.rbtReceived.TabIndex = 1;
			this.rbtReceived.TabStop = true;
			this.rbtReceived.Text = "Recibidos";
			this.rbtReceived.UseVisualStyleBackColor = true;
			this.rbtSended.AutoSize = true;
			this.rbtSended.Location = new Point(3, 1);
			this.rbtSended.Name = "rbtSended";
			this.rbtSended.Size = new System.Drawing.Size(64, 17);
			this.rbtSended.TabIndex = 0;
			this.rbtSended.Text = "Emitidos";
			this.rbtSended.UseVisualStyleBackColor = true;
			this.groupBox4.Controls.Add(this.cmbAccount);
			this.groupBox4.Controls.Add(this.label1);
			this.groupBox4.Controls.Add(this.txtPassword);
			this.groupBox4.Controls.Add(this.label2);
			this.groupBox4.Location = new Point(12, 27);
			this.groupBox4.Name = "groupBox4";
			this.groupBox4.Size = new System.Drawing.Size(199, 105);
			this.groupBox4.TabIndex = 0;
			this.groupBox4.TabStop = false;
			this.groupBox4.Text = "Autentificación";
			this.cmbAccount.DropDownStyle = ComboBoxStyle.DropDownList;
			this.cmbAccount.FormattingEnabled = true;
			this.cmbAccount.Location = new Point(74, 17);
			this.cmbAccount.Name = "cmbAccount";
			this.cmbAccount.Size = new System.Drawing.Size(112, 21);
			this.cmbAccount.TabIndex = 9;
			this.txtLog.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
			this.txtLog.Location = new Point(12, 158);
			this.txtLog.Multiline = true;
			this.txtLog.Name = "txtLog";
			this.txtLog.ReadOnly = true;
			this.txtLog.ScrollBars = ScrollBars.Vertical;
			this.txtLog.Size = new System.Drawing.Size(865, 224);
			this.txtLog.TabIndex = 8;
			this.txtLog.KeyDown += new KeyEventHandler(this.txtLog_KeyDown);
			this.lblStatus.AutoSize = true;
			this.lblStatus.Font = new System.Drawing.Font("Microsoft Sans Serif", 12f, FontStyle.Regular, GraphicsUnit.Point, 0);
			this.lblStatus.Location = new Point(12, 135);
			this.lblStatus.Name = "lblStatus";
			this.lblStatus.Size = new System.Drawing.Size(71, 20);
			this.lblStatus.TabIndex = 9;
			this.lblStatus.Text = "lblStatus";
			ToolStripItemCollection toolStripItemCollections = this.menuStrip1.Items;
			ToolStripItem[] toolStripItemArray = new ToolStripItem[] { this.configuraciónToolStripMenuItem };
			toolStripItemCollections.AddRange(toolStripItemArray);
			this.menuStrip1.Location = new Point(0, 0);
			this.menuStrip1.Name = "menuStrip1";
			this.menuStrip1.Size = new System.Drawing.Size(884, 24);
			this.menuStrip1.TabIndex = 10;
			this.menuStrip1.Text = "menuStrip1";
			ToolStripItemCollection dropDownItems = new ToolStripItemCollection();
            dropDownItems= this.configuraciónToolStripMenuItem.DropDownItems;
			toolStripItemArray = new ToolStripItem[] { this.licenciaToolStripMenuItem };
			dropDownItems.AddRange(toolStripItemArray);
			this.configuraciónToolStripMenuItem.Name = "configuraciónToolStripMenuItem";
			this.configuraciónToolStripMenuItem.Size = new System.Drawing.Size(95, 20);
			this.configuraciónToolStripMenuItem.Text = "Configuración";
			this.licenciaToolStripMenuItem.Name = "licenciaToolStripMenuItem";
			this.licenciaToolStripMenuItem.Size = new System.Drawing.Size(117, 22);
			this.licenciaToolStripMenuItem.Text = "Licencia";
			this.licenciaToolStripMenuItem.Click += new EventHandler(this.licenciaToolStripMenuItem_Click);
			base.AutoScaleDimensions = new SizeF(6f, 13f);
			base.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			base.ClientSize = new System.Drawing.Size(884, 411);
			base.Controls.Add(this.lblStatus);
			base.Controls.Add(this.txtLog);
			base.Controls.Add(this.groupBox4);
			base.Controls.Add(this.groupBox3);
			base.Controls.Add(this.groupBox2);
			base.Controls.Add(this.statusStrip1);
			base.Controls.Add(this.menuStrip1);
			base.MainMenuStrip = this.menuStrip1;
			base.Name = "FrmDownloadXml";
			this.Text = "Descarga de XML";
			this.groupBox2.ResumeLayout(false);
			this.groupBox2.PerformLayout();
			this.groupBox3.ResumeLayout(false);
			this.groupBox3.PerformLayout();
			this.panel1.ResumeLayout(false);
			this.panel1.PerformLayout();
			this.groupBox4.ResumeLayout(false);
			this.groupBox4.PerformLayout();
			this.menuStrip1.ResumeLayout(false);
			this.menuStrip1.PerformLayout();
			base.ResumeLayout(false);
			base.PerformLayout();
		}

		private void licenciaToolStripMenuItem_Click(object sender, EventArgs e)
		{
			try
			{
				if ((new FrmAddAccount()).ShowDialog() == System.Windows.Forms.DialogResult.OK)
				{
					this.InitControls();
				}
			}
			catch (Exception exception)
			{
				MessageBox.Show(exception.Message);
			}
		}

		private void Message(string message)
		{
			try
			{
				this.lblStatus.Text = message;
				this.txtLog.AppendText(string.Concat(message, "\n"));
			}
			catch (Exception exception)
			{
				MessageBox.Show(exception.Message);
			}
		}

		private void ProcessResult()
		{
			DateTime dateTime;
			string str1;
			bool flag;
			string str2;
			try
			{
				Regex regex = new Regex("'.*?'");
				if (!(this._wbSat.Document == null))
				{
					HtmlElementCollection elementsByTagName = this._wbSat.Document.GetElementsByTagName("table");
					foreach (HtmlElement htmlElement in elementsByTagName)
					{
						foreach (HtmlElement elementsByTagName1 in htmlElement.GetElementsByTagName("tr"))
						{
							HtmlElementCollection elementsByName = elementsByTagName1.GetElementsByTagName("img").GetElementsByName("BtnDescarga");
							if (elementsByName.Count == 1)
							{
								string str3 = string.Format("https://portalcfdi.facturaelectronica.sat.gob.mx/{0}", regex.Match(elementsByName[0].OuterHtml).Value.Replace("'", ""));
								IEnumerable<HtmlElement> htmlElements = elementsByTagName1.GetElementsByTagName("span").Cast<HtmlElement>();
								IEnumerable<HtmlElement> htmlElements1 = htmlElements.Where<HtmlElement>((HtmlElement span) => {
									bool innerText = span.InnerText != "";
									return innerText;
								});
								string str4 = htmlElements1.Aggregate<HtmlElement, string>("", (string current, HtmlElement span) => {
									string str = string.Concat(current, span.InnerText, "|");
									return str;
								});
								char[] chrArray = new char[] { '|' };
								string[] strArrays = str4.Split(chrArray);
								DateTime.TryParse(strArrays[5], out dateTime);
								string[] text = new string[] { this.lblDownloadPath.Text, this.cmbAccount.SelectedItem.ToString(), null, null, null, null };
								string[] strArrays1 = text;
								str1 = (this.rbtReceived.Checked ? "Received" : "Sended");
								strArrays1[2] = str1;
								int year = dateTime.Year;
								text[3] = year.ToString("0000");
								year = dateTime.Month;
								text[4] = year.ToString("00");
								year = dateTime.Day;
								text[5] = year.ToString("00");
								string str5 = Path.Combine(text);
								if (!Directory.Exists(str5))
								{
									Directory.CreateDirectory(str5);
								}
								string str6 = Path.Combine(str5, string.Format("{0}_{1}_{2}.xml", strArrays[1], strArrays[3], strArrays[0]));
								this.DownloadFile(str3, str6);
								flag = (!this._supplierStructure ? true : !this.rbtReceived.Checked);
								if (!flag)
								{
									text = new string[] { this.lblDownloadPath.Text, this.cmbAccount.SelectedItem.ToString(), null, null, null, null, null };
									string[] strArrays2 = text;
									str2 = (this.rbtReceived.Checked ? "Received" : "Sended");
									strArrays2[2] = str2;
									text[3] = strArrays[1];
									year = dateTime.Year;
									text[4] = year.ToString("0000");
									year = dateTime.Month;
									text[5] = year.ToString("00");
									year = dateTime.Day;
									text[6] = year.ToString("00");
									str5 = Path.Combine(text);
									if (!Directory.Exists(str5))
									{
										Directory.CreateDirectory(str5);
									}
									str6 = Path.Combine(str5, string.Format("{0}_{1}_{2}.xml", strArrays[1], strArrays[3], strArrays[0]));
									this.DownloadFile(str3, str6);
								}
							}
						}
					}
				}
				else
				{
					return;
				}
			}
			catch (Exception exception)
			{
				throw new Exception(exception.Message);
			}
		}

		private void txtLog_KeyDown(object sender, KeyEventArgs e)
		{
            //bool flag;
            //bool flag1;
            //flag1 = (e.KeyData == (Keys.LButton | Keys.A | Keys.Control) ? false : e.KeyData != (Keys.LButton | Keys.MButton | Keys.XButton1 | Keys.A | Keys.D | Keys.E | Keys.Control));
            //if (!flag1)
            //{
            //    this.txtLog.SelectAll();
            //    int num = 1;
            //    flag = (bool)num;
            //    e.SuppressKeyPress = (bool)num;
            //    e.Handled = flag;
            //}
            //if (e.KeyData == (Keys.LButton | Keys.RButton | Keys.Cancel | Keys.A | Keys.B | Keys.C | Keys.Control))
            //{
            //    Clipboard.SetText(this.txtLog.SelectedText);
            //    int num1 = 1;
            //    flag = (bool)num1;
            //    e.SuppressKeyPress = (bool)num1;
            //    e.Handled = flag;
            //}
		}

		private void txtPassword_Enter(object sender, EventArgs e)
		{
			if (this.txtPassword.Text.Trim() != "")
			{
				this.lblStatus.Text = "";
				this.txtPassword.SelectAll();
			}
		}

		private void wbSAT_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
		{
			int selectedItem;
			int num;
			int selectedItem1;
			int i;
			int j;
			bool flag;
			bool flag1;
			if (this._wbSat.Document != null)
			{
				if (this._wbSat.Url == new Uri("https://cfdiau.sat.gob.mx/nidp/app?sid=0"))
				{
					this.Message(string.Format("Usuario {0} Autentificado correctamente.", this.cmbAccount.SelectedItem));
					if (this.rbtReceived.Checked)
					{
						this._wbSat.Navigate("https://portalcfdi.facturaelectronica.sat.gob.mx/ConsultaReceptor.aspx");
					}
					if (this.rbtSended.Checked)
					{
						this._wbSat.Navigate("https://portalcfdi.facturaelectronica.sat.gob.mx/ConsultaEmisor.aspx");
					}
				}
				if (this._wbSat.Url == new Uri("https://cfdiau.sat.gob.mx/nidp/app/login?sid=0&sid=0"))
				{
					this.txtPassword.Focus();
					this.txtPassword.SelectionStart = 0;
					this.txtPassword.SelectionLength = this.txtPassword.Text.Length;
					this.Message("Clave CIEC incorrecta, favor de verificar RFC y Clave.");
				}
				flag = (this._wbSat.Url != new Uri("https://portalcfdi.facturaelectronica.sat.gob.mx/ConsultaReceptor.aspx") ? true : !(this._wbSat.Url != new Uri(this._currentUrl)));
				if (!flag)
				{
					selectedItem = (int)this.cmbYear.SelectedItem;
					num = int.Parse(this.cmbInitial.SelectedItem.ToString());
					selectedItem1 = int.Parse(this.cmbEnd.SelectedItem.ToString());
					for (i = num; i <= selectedItem1; i++)
					{
						if (!this.rbtDay.Checked)
						{
							this.Message(string.Format("Procesando documentos recibidos del ejercicio {0}, periodo {1} ...", selectedItem, i));
							this.GetReceivedDocuments(selectedItem, i);
						}
						else
						{
							for (j = 1; j <= DateTime.DaysInMonth(selectedItem, i); j++)
							{
								this.Message(string.Format("Procesando documentos recibidos de la fecha  {0}/{1}/{2} ...", j.ToString("00"), i.ToString("00"), selectedItem));
								this.GetReceivedDocuments(selectedItem, i, j);
							}
						}
					}
					this.FinishSession();
				}
				flag1 = (this._wbSat.Url != new Uri("https://portalcfdi.facturaelectronica.sat.gob.mx/ConsultaEmisor.aspx") ? true : !(this._wbSat.Url != new Uri(this.lblStatus.Text)));
				if (!flag1)
				{
					selectedItem = (int)this.cmbYear.SelectedItem;
					num = (int)this.cmbInitial.SelectedItem;
					selectedItem1 = (int)this.cmbEnd.SelectedItem;
					for (i = num; i <= selectedItem1; i++)
					{
						if (!this.rbtDay.Checked)
						{
							this.Message(string.Format("Procesando documentos emitidos del ejercicio {0}, periodo {1} ...", selectedItem, i));
							this.GetSendedDocuments(selectedItem, i);
						}
						else
						{
							for (j = 1; j <= DateTime.DaysInMonth(selectedItem, i); j++)
							{
								this.Message(string.Format("Procesando documentos emitidos de la fecha  {0}/{1}/{2} ...", j, i, selectedItem));
								this.GetSendedDocuments(selectedItem, i, j);
							}
						}
					}
					this.FinishSession();
				}
				while (true)
				{
					Application.DoEvents();
					if (!this._wbSat.IsBusy)
					{
						break;
					}
				}
				this._currentUrl = this._wbSat.Url.ToString();
			}
		}
	}
}