using System;
using System.Collections;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Threading;

using nsAlienRFID2;


namespace Ex5
{
	public delegate void displayMessageDlgt(string msg);

	public class Form1 : System.Windows.Forms.Form
	{
		private clsReaderMonitor mMonitor;
        private Dictionary<string, IReaderInfo> mdReaders = new Dictionary<string, IReaderInfo>();

		#region "Auto-generated code"

		private System.Windows.Forms.RichTextBox richTextBox1;
		private System.Windows.Forms.Button btnStart;
		private System.Windows.Forms.Button btnRdrList;
		private System.Windows.Forms.Button btnStop;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.Label label2;
        private System.Windows.Forms.NumericUpDown PortUD;
		private System.Windows.Forms.DataGrid dataGrid1;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ToolTip toolTip1;
		private System.Windows.Forms.Button btnClear;
		private System.Windows.Forms.NumericUpDown UpdateUD;
		private System.Windows.Forms.Label label4;
        private ListView lsvReaders;
		private System.ComponentModel.IContainer components;

		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            this.richTextBox1 = new System.Windows.Forms.RichTextBox();
            this.btnStart = new System.Windows.Forms.Button();
            this.btnRdrList = new System.Windows.Forms.Button();
            this.btnStop = new System.Windows.Forms.Button();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.PortUD = new System.Windows.Forms.NumericUpDown();
            this.dataGrid1 = new System.Windows.Forms.DataGrid();
            this.label3 = new System.Windows.Forms.Label();
            this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
            this.btnClear = new System.Windows.Forms.Button();
            this.UpdateUD = new System.Windows.Forms.NumericUpDown();
            this.label4 = new System.Windows.Forms.Label();
            this.lsvReaders = new System.Windows.Forms.ListView();
            ((System.ComponentModel.ISupportInitialize)(this.PortUD)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.UpdateUD)).BeginInit();
            this.SuspendLayout();
            // 
            // richTextBox1
            // 
            this.richTextBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)));
            this.richTextBox1.BackColor = System.Drawing.SystemColors.WindowFrame;
            this.richTextBox1.Cursor = System.Windows.Forms.Cursors.Arrow;
            this.richTextBox1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.richTextBox1.Location = new System.Drawing.Point(20, 49);
            this.richTextBox1.Name = "richTextBox1";
            this.richTextBox1.Size = new System.Drawing.Size(260, 143);
            this.richTextBox1.TabIndex = 4;
            this.richTextBox1.Text = "";
            this.toolTip1.SetToolTip(this.richTextBox1, "Monitors all readers on the network");
            // 
            // btnStart
            // 
            this.btnStart.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.btnStart.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnStart.Location = new System.Drawing.Point(306, 24);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(113, 34);
            this.btnStart.TabIndex = 9;
            this.btnStart.Text = "&Start Listening";
            this.toolTip1.SetToolTip(this.btnStart, "Starts network monitoring");
            this.btnStart.UseVisualStyleBackColor = false;
            this.btnStart.Click += new System.EventHandler(this.btnStart_Click);
            // 
            // btnRdrList
            // 
            this.btnRdrList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.btnRdrList.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnRdrList.Location = new System.Drawing.Point(306, 142);
            this.btnRdrList.Name = "btnRdrList";
            this.btnRdrList.Size = new System.Drawing.Size(114, 34);
            this.btnRdrList.TabIndex = 10;
            this.btnRdrList.Text = "Get &Reader List";
            this.toolTip1.SetToolTip(this.btnRdrList, "Gets most recent Readers\' List");
            this.btnRdrList.UseVisualStyleBackColor = false;
            this.btnRdrList.Click += new System.EventHandler(this.btnRdrList_Click);
            // 
            // btnStop
            // 
            this.btnStop.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.btnStop.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnStop.Location = new System.Drawing.Point(306, 64);
            this.btnStop.Name = "btnStop";
            this.btnStop.Size = new System.Drawing.Size(113, 35);
            this.btnStop.TabIndex = 11;
            this.btnStop.Text = "Sto&p Listening";
            this.toolTip1.SetToolTip(this.btnStop, "Stops network monitoring");
            this.btnStop.UseVisualStyleBackColor = false;
            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
            // 
            // label1
            // 
            this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label1.Location = new System.Drawing.Point(25, 33);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(173, 20);
            this.label1.TabIndex = 24;
            this.label1.Text = "Network Monitoring on Port#: ";
            // 
            // label2
            // 
            this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label2.Location = new System.Drawing.Point(447, 32);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(86, 21);
            this.label2.TabIndex = 25;
            this.label2.Text = "Reader List:";
            // 
            // PortUD
            // 
            this.PortUD.BackColor = System.Drawing.SystemColors.Info;
            this.PortUD.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.PortUD.Location = new System.Drawing.Point(184, 32);
            this.PortUD.Maximum = new decimal(new int[] {
            10000,
            0,
            0,
            0});
            this.PortUD.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.PortUD.Name = "PortUD";
            this.PortUD.Size = new System.Drawing.Size(56, 19);
            this.PortUD.TabIndex = 27;
            this.PortUD.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.PortUD.Value = new decimal(new int[] {
            3988,
            0,
            0,
            0});
            this.PortUD.ValueChanged += new System.EventHandler(this.PortUD_ValueChanged);
            // 
            // dataGrid1
            // 
            this.dataGrid1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.dataGrid1.BackgroundColor = System.Drawing.SystemColors.WindowFrame;
            this.dataGrid1.CaptionBackColor = System.Drawing.SystemColors.Info;
            this.dataGrid1.CaptionForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid1.CaptionVisible = false;
            this.dataGrid1.DataMember = "";
            this.dataGrid1.ForeColor = System.Drawing.SystemColors.MenuText;
            this.dataGrid1.HeaderBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid1.Location = new System.Drawing.Point(24, 244);
            this.dataGrid1.Name = "dataGrid1";
            this.dataGrid1.RowHeadersVisible = false;
            this.dataGrid1.Size = new System.Drawing.Size(677, 69);
            this.dataGrid1.TabIndex = 30;
            this.toolTip1.SetToolTip(this.dataGrid1, "Displays details for selected reader");
            // 
            // label3
            // 
            this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.label3.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label3.Location = new System.Drawing.Point(24, 229);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(168, 21);
            this.label3.TabIndex = 31;
            this.label3.Text = "Selected Reader\'s Details:";
            // 
            // btnClear
            // 
            this.btnClear.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.btnClear.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.btnClear.Location = new System.Drawing.Point(306, 182);
            this.btnClear.Name = "btnClear";
            this.btnClear.Size = new System.Drawing.Size(114, 34);
            this.btnClear.TabIndex = 32;
            this.btnClear.Text = "&Clear Reader List";
            this.toolTip1.SetToolTip(this.btnClear, "Clears Readers\' List");
            this.btnClear.UseVisualStyleBackColor = false;
            this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
            // 
            // UpdateUD
            // 
            this.UpdateUD.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.UpdateUD.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.UpdateUD.Location = new System.Drawing.Point(645, 32);
            this.UpdateUD.Maximum = new decimal(new int[] {
            60,
            0,
            0,
            0});
            this.UpdateUD.Minimum = new decimal(new int[] {
            1,
            0,
            0,
            0});
            this.UpdateUD.Name = "UpdateUD";
            this.UpdateUD.Size = new System.Drawing.Size(56, 19);
            this.UpdateUD.TabIndex = 51;
            this.UpdateUD.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.UpdateUD.ThousandsSeparator = true;
            this.toolTip1.SetToolTip(this.UpdateUD, "Time");
            this.UpdateUD.Value = new decimal(new int[] {
            5,
            0,
            0,
            0});
            this.UpdateUD.ValueChanged += new System.EventHandler(this.UpdateUD_ValueChanged);
            // 
            // label4
            // 
            this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label4.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.label4.Location = new System.Drawing.Point(554, 32);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(96, 19);
            this.label4.TabIndex = 50;
            this.label4.Text = "Update Time (sec): ";
            // 
            // lsvReaders
            // 
            this.lsvReaders.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.lsvReaders.BackColor = System.Drawing.Color.Black;
            this.lsvReaders.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(192)))));
            this.lsvReaders.Location = new System.Drawing.Point(445, 49);
            this.lsvReaders.MultiSelect = false;
            this.lsvReaders.Name = "lsvReaders";
            this.lsvReaders.Size = new System.Drawing.Size(256, 143);
            this.lsvReaders.TabIndex = 52;
            this.lsvReaders.UseCompatibleStateImageBehavior = false;
            this.lsvReaders.View = System.Windows.Forms.View.List;
            this.lsvReaders.SelectedIndexChanged += new System.EventHandler(this.lsvReaders_SelectedIndexChanged);
            this.lsvReaders.MouseEnter += new System.EventHandler(this.lsvReaders_MouseEnter);
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.BackColor = System.Drawing.SystemColors.ControlText;
            this.ClientSize = new System.Drawing.Size(731, 340);
            this.Controls.Add(this.lsvReaders);
            this.Controls.Add(this.btnClear);
            this.Controls.Add(this.dataGrid1);
            this.Controls.Add(this.PortUD);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.btnStop);
            this.Controls.Add(this.btnRdrList);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.richTextBox1);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.UpdateUD);
            this.Controls.Add(this.label4);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);
            ((System.ComponentModel.ISupportInitialize)(this.PortUD)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.UpdateUD)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
				Application.Run(new Form1());
		}

		#endregion

		private void Form1_Load(object sender, System.EventArgs e)
		{
            #region "Application title"
			Thread.CurrentThread.Name = "Alien-Ex5: Test Network Discovery";
			this.Text = "Alien Library .NET - Testing Network Discovery Example";
			#endregion

			mMonitor = new clsReaderMonitor();
			mMonitor.ComPortsMonitoring = false;	//just for demo, it IS false by default
			mMonitor.NetworkMonitoring = true;

			UpdateUD.Value = (decimal)mMonitor.UpdateInterval / 1000;

			//	Subscribe to clsReaderMonitor events
			mMonitor.ReaderAdded += 
				new clsReaderMonitor.ReaderAddedEventHandler(mMonitor_ReaderAdded);
			mMonitor.ReaderRenewed += 
				new clsReaderMonitor.ReaderRenewedEventHandler(mMonitor_ReaderRenewed);
			mMonitor.ReaderRemoved += 
				new clsReaderMonitor.ReaderRemovedEventHandler(mMonitor_ReaderRemoved);
		}
		
		private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			mMonitor.StopListening();
			mMonitor = null;
		}


		private void DisplayText(String data)
		{
			try
			{
				if (this.InvokeRequired)
				{
					object[] temp = {data};
					this.Invoke(new displayMessageDlgt(DisplayText),temp);
					return;
				}
				else
				{	
					richTextBox1.Text += (data + "\r\n");
					richTextBox1.SelectionStart = richTextBox1.Text.Length;
					richTextBox1.SelectionLength = 0;
					richTextBox1.Focus();
					richTextBox1.ScrollToCaret();
					this.Cursor = Cursors.Default;
					return;
				}
			}
			catch(Exception ex)
			{
				Debug.WriteLine("Exception in the DiscplayText: " + ex.Message);
			}
		}

		
		private void mMonitor_ReaderAdded(IReaderInfo data)
		{
			DisplayText(data.Name + " - has been added");
		}

		private void mMonitor_ReaderRenewed(IReaderInfo data)
		{
			DisplayText(data.Name + " - has been renewed");
		}

		private void mMonitor_ReaderRemoved(IReaderInfo data)
		{
			DisplayText(data.Name + " - has been LOST");
		}

		
		private void btnStart_Click(object sender, System.EventArgs e)
		{
			this.Cursor = Cursors.WaitCursor;
			mMonitor.StartListening();
		}

		private void btnRdrList_Click(object sender, System.EventArgs e)
		{
			IReaderInfo[] rs;
			this.Cursor = Cursors.WaitCursor;
			lsvReaders.Clear();
			String response = mMonitor.GetReaderList(out rs);
			if (response != "")
				richTextBox1.AppendText(response + "\r\n\n");
			else
			{
				for (int i = 0; i < rs.Length; i++)
				{
                    string mac = rs[i].MACAddress;
                    if (!mdReaders.ContainsKey(mac))
                        mdReaders.Add(mac, rs[i]);

                    ListViewItem item = new ListViewItem(rs[i].Name);
                    item.Tag = mac;
                    lsvReaders.Items.Add(item);
				}
			}
			this.Cursor = Cursors.Default;
		}

		private void btnStop_Click(object sender, System.EventArgs e)
		{
			mMonitor.StopListening();
			this.Cursor = Cursors.Default;
		}

		private void PortUD_ValueChanged(object sender, System.EventArgs e)
		{
			mMonitor.Port = (int)PortUD.Value;	
		}

		private void btnClear_Click(object sender, System.EventArgs e)
		{
			mMonitor.ClearAllReaders();
			lsvReaders.Clear();
			richTextBox1.Clear();
		}

		private void UpdateUD_ValueChanged(object sender, System.EventArgs e)
		{
			mMonitor.UpdateInterval = (int)UpdateUD.Value * 1000;
		}

        private void lsvReaders_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lsvReaders.SelectedItems.Count == 0)
                return;
            string mac = lsvReaders.SelectedItems[0].Tag as string;

            if (mdReaders.ContainsKey(mac))
            {
                ArrayList al = new ArrayList(1);
                al.Add(mdReaders[mac]);
                dataGrid1.DataSource = al;
                dataGrid1.CaptionText = "Selected Reader's Settings:";
            }
        }

        private void lsvReaders_MouseEnter(object sender, EventArgs e)
        {
			if (lsvReaders.Items.Count > 0)
			{
				lsvReaders.Cursor = Cursors.Hand;
				this.toolTip1.SetToolTip(this.lsvReaders, "Click a reader for detail information");
			}
			else
			{
				lsvReaders.Cursor = Cursors.Default;
				this.toolTip1.SetToolTip(this.lsvReaders, "There are no readers for displaying detail information");
			}
        }


	}
}
