using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using CdigCs;

namespace LoadConfig
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		/// <summary>
		/// Creat the instance of class Cdig
		/// </summary>
		Cdig  dig = new Cdig();
		public const int	MAX_SAMPLES = 1024;				// The definition of the maximum number of acquiring samples  : 1024

		public short	m_Id;								// Device ID
		public float[]	m_Data = new float[MAX_SAMPLES];	// Array of retrieving data
		public int		m_Records;							// Number of retrieved record
		public float	m_Range;							// Input voltage range
		public int		m_RecordLength;						// Record length
		public short	m_TriggerChannel;					// Post-trigger channel
		public short	m_Channels;							// Number of effective channels
		public Bitmap	bmp;								// Bitmap

		private System.Windows.Forms.Button buttonLoad;
		private System.Windows.Forms.Label labelStatus;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.PictureBox Graph;
		private System.Windows.Forms.TextBox textBoxDeviceInfo;
		private System.Windows.Forms.TextBox textBoxInfo;
		private System.Windows.Forms.Button buttonExit;
		private System.Windows.Forms.Button buttonStop;
		private System.Windows.Forms.Button buttonInfo;
		private System.Windows.Forms.Button buttonStart;
		private System.Windows.Forms.Button buttonInit;
		private System.Windows.Forms.TextBox textBoxDevice;
		private System.Windows.Forms.Label label1;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

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

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			bmp = new Bitmap(Graph.Size.Width, Graph.Size.Height);	// Create the bitmap which is compatible with the graph
		}

		/// <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.buttonLoad = new System.Windows.Forms.Button();
            this.labelStatus = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.Graph = new System.Windows.Forms.PictureBox();
            this.textBoxDeviceInfo = new System.Windows.Forms.TextBox();
            this.textBoxInfo = new System.Windows.Forms.TextBox();
            this.buttonExit = new System.Windows.Forms.Button();
            this.buttonStop = new System.Windows.Forms.Button();
            this.buttonInfo = new System.Windows.Forms.Button();
            this.buttonStart = new System.Windows.Forms.Button();
            this.buttonInit = new System.Windows.Forms.Button();
            this.textBoxDevice = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            ((System.ComponentModel.ISupportInitialize)(this.Graph)).BeginInit();
            this.SuspendLayout();
            // 
            // buttonLoad
            // 
            this.buttonLoad.Location = new System.Drawing.Point(8, 94);
            this.buttonLoad.Name = "buttonLoad";
            this.buttonLoad.Size = new System.Drawing.Size(112, 26);
            this.buttonLoad.TabIndex = 2;
            this.buttonLoad.Text = "Read Configuration";
            this.buttonLoad.Click += new System.EventHandler(this.buttonLoad_Click);
            // 
            // labelStatus
            // 
            this.labelStatus.Location = new System.Drawing.Point(312, 277);
            this.labelStatus.Name = "labelStatus";
            this.labelStatus.Size = new System.Drawing.Size(112, 18);
            this.labelStatus.TabIndex = 56;
            this.labelStatus.Text = "0H";
            // 
            // label2
            // 
            this.label2.Location = new System.Drawing.Point(264, 277);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(40, 18);
            this.label2.TabIndex = 55;
            this.label2.Text = "Status";
            // 
            // Graph
            // 
            this.Graph.BackColor = System.Drawing.Color.White;
            this.Graph.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.Graph.Location = new System.Drawing.Point(128, 9);
            this.Graph.Name = "Graph";
            this.Graph.Size = new System.Drawing.Size(304, 262);
            this.Graph.TabIndex = 54;
            this.Graph.TabStop = false;
            // 
            // textBoxDeviceInfo
            // 
            this.textBoxDeviceInfo.Cursor = System.Windows.Forms.Cursors.IBeam;
            this.textBoxDeviceInfo.Location = new System.Drawing.Point(216, 295);
            this.textBoxDeviceInfo.Multiline = true;
            this.textBoxDeviceInfo.Name = "textBoxDeviceInfo";
            this.textBoxDeviceInfo.ReadOnly = true;
            this.textBoxDeviceInfo.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.textBoxDeviceInfo.Size = new System.Drawing.Size(216, 80);
            this.textBoxDeviceInfo.TabIndex = 8;
            // 
            // textBoxInfo
            // 
            this.textBoxInfo.Location = new System.Drawing.Point(8, 295);
            this.textBoxInfo.Multiline = true;
            this.textBoxInfo.Name = "textBoxInfo";
            this.textBoxInfo.ReadOnly = true;
            this.textBoxInfo.Size = new System.Drawing.Size(216, 80);
            this.textBoxInfo.TabIndex = 7;
            // 
            // buttonExit
            // 
            this.buttonExit.Location = new System.Drawing.Point(8, 233);
            this.buttonExit.Name = "buttonExit";
            this.buttonExit.Size = new System.Drawing.Size(112, 26);
            this.buttonExit.TabIndex = 6;
            this.buttonExit.Text = "Exit";
            this.buttonExit.Click += new System.EventHandler(this.buttonExit_Click);
            // 
            // buttonStop
            // 
            this.buttonStop.Location = new System.Drawing.Point(8, 198);
            this.buttonStop.Name = "buttonStop";
            this.buttonStop.Size = new System.Drawing.Size(112, 26);
            this.buttonStop.TabIndex = 5;
            this.buttonStop.Text = "Stop Acquisition";
            this.buttonStop.Click += new System.EventHandler(this.buttonStop_Click);
            // 
            // buttonInfo
            // 
            this.buttonInfo.Location = new System.Drawing.Point(8, 164);
            this.buttonInfo.Name = "buttonInfo";
            this.buttonInfo.Size = new System.Drawing.Size(112, 26);
            this.buttonInfo.TabIndex = 4;
            this.buttonInfo.Text = "Get Information";
            this.buttonInfo.Click += new System.EventHandler(this.buttonInfo_Click);
            // 
            // buttonStart
            // 
            this.buttonStart.Location = new System.Drawing.Point(8, 129);
            this.buttonStart.Name = "buttonStart";
            this.buttonStart.Size = new System.Drawing.Size(112, 26);
            this.buttonStart.TabIndex = 3;
            this.buttonStart.Text = "Start Acquisition";
            this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
            // 
            // buttonInit
            // 
            this.buttonInit.Location = new System.Drawing.Point(8, 60);
            this.buttonInit.Name = "buttonInit";
            this.buttonInit.Size = new System.Drawing.Size(112, 26);
            this.buttonInit.TabIndex = 1;
            this.buttonInit.Text = "Init";
            this.buttonInit.Click += new System.EventHandler(this.buttonInit_Click);
            // 
            // textBoxDevice
            // 
            this.textBoxDevice.Location = new System.Drawing.Point(8, 25);
            this.textBoxDevice.Name = "textBoxDevice";
            this.textBoxDevice.Size = new System.Drawing.Size(72, 20);
            this.textBoxDevice.TabIndex = 0;
            this.textBoxDevice.Text = "DIG000";
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(8, 9);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(72, 17);
            this.label1.TabIndex = 45;
            this.label1.Text = "Device Name";
            // 
            // Form1
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(440, 383);
            this.Controls.Add(this.buttonLoad);
            this.Controls.Add(this.labelStatus);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.Graph);
            this.Controls.Add(this.textBoxDeviceInfo);
            this.Controls.Add(this.textBoxInfo);
            this.Controls.Add(this.buttonExit);
            this.Controls.Add(this.buttonStop);
            this.Controls.Add(this.buttonInfo);
            this.Controls.Add(this.buttonStart);
            this.Controls.Add(this.buttonInit);
            this.Controls.Add(this.textBoxDevice);
            this.Controls.Add(this.label1);
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.Text = "Load Configuration File";
            this.Closed += new System.EventHandler(this.Form1_Closed);
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.Graph)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

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

		/// <summary>
		/// Init handling
		/// </summary>
		private void buttonInit_Click(object sender, System.EventArgs e)
		{
			int		Ret;
			string	ErrorString;

			//--------------------------------
			// Init handling
			//--------------------------------
			Ret = dig.Init(textBoxDevice.Text, out m_Id);
			if(Ret != 0)
			{
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.Init = " + Ret.ToString() + " : " + ErrorString;
				return;
			}

			//--------------------------------
			// Reset device
			//--------------------------------
			Ret = dig.ResetDevice(m_Id);
			if(Ret != 0)
			{
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.ResetDevice = " + Ret.ToString() + " : " + ErrorString;
				return;
			}

			textBoxInfo.Text = "Init : Normality completion";		
		}

		/// <summary>
		/// Read setting file
		/// </summary>
		private void buttonLoad_Click(object sender, System.EventArgs e)
		{
			int		Ret;		// Return value
			string	FilePath;	// File path

			//----------------------------------
			// Show FileOpen dialog
			//----------------------------------
			OpenFileDialog LoadDialog = new OpenFileDialog();

			// Determines the choices that appear in the "Save as file type" or "Files of type" box in the dialog box
			LoadDialog.Filter = "xml files (*.xml)|*.xml";
			if(LoadDialog.ShowDialog() == DialogResult.OK)
			{
				FilePath = LoadDialog.FileName;		// Get the file path
				Ret = dig.LoadConfig(m_Id, FilePath);
				if(Ret != 0)
				{
					string ErrorString;
					dig.GetErrorString(Ret, out ErrorString);
					textBoxInfo.Text = "dig.Start = " + Ret.ToString() + " : " + ErrorString;
					return;
				}
				textBoxInfo.Text = "Read Setting file : Normality completion";
			}		
		}

		/// <summary>
		/// Start acquisition
		/// </summary>
		private void buttonStart_Click(object sender, System.EventArgs e)
		{
			int		Ret;		// Return value

			//---------------------------------
			// Initialize variable
			//---------------------------------
			m_Records = 0;

			//---------------------------------
			// Get the setup information and display
			//---------------------------------
			buttonInfo_Click(buttonInfo, new System.EventArgs());

			//---------------------------------
			// Operation start
			//---------------------------------
			Ret = dig.Start(m_Id);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.Start = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			textBoxInfo.Text = "Start acquisition : Normality completion";		

			//---------------------------------
			// Polling until the operation status is changed to be OFF
			//---------------------------------
			int Status;

			do
			{
				//---------------------------------
				// In order to enable the dialog operation
				//---------------------------------
				System.Windows.Forms.Application.DoEvents();
				//---------------------------------
				// Get the number of records which are being stored in driver memory
				//---------------------------------
				Ret = dig.GetDriverMemoryRecords(m_Id, out m_Records);
				if(Ret != 0)
				{
					string ErrorString;
					dig.GetErrorString(Ret, out ErrorString);
					textBoxInfo.Text = "dig.GetDriverMemoryRecords = " + Ret.ToString() + " : " + ErrorString;
					return;
				}
				//---------------------------------
				// If there are records in driver memory, retrieve the data from the new side
				//---------------------------------
				if(m_Records > 0 || m_Records == -1)
				{
					Ret = dig.ReadLatestRecords(m_Id, Cdig.DIG_RECORD_DATA, 1, ref m_Data, 0, 0);
					if(Ret != 0)
					{
						string ErrorString;
						dig.GetErrorString(Ret, out ErrorString);
						textBoxInfo.Text = "dig.ReadLatestRecordss = " + Ret.ToString() + " : " + ErrorString;
						return;
					}
					//------------------------------------
					// Draw graph
					//------------------------------------
					DrawGraph();
				}
				//---------------------------------
				// Get the operation status
				//---------------------------------
				Ret = dig.GetStatus(m_Id, out Status);
				if(Ret != 0)
				{
					string ErrorString;
					dig.GetErrorString(Ret, out ErrorString);
					textBoxInfo.Text = "dig.GetStatus = " + Ret.ToString() + " : " + ErrorString;
					return;
				}
				labelStatus.Text = Status.ToString("X") + "H";
			}while((Status & Cdig.DIG_STATUS_BUSY) == Cdig.DIG_STATUS_BUSY);
			//---------------------------------
			// After operation stop, get the number of records which are being stored in driver memory
			//---------------------------------
			Ret = dig.GetDriverMemoryRecords(m_Id, out m_Records);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetDriverMemoryRecords = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			//---------------------------------
			// If there are records in driver memory, retrieve the data
			//---------------------------------
			if(m_Records > 0)
			{
				Ret = dig.ReadLatestRecords(m_Id, Cdig.DIG_RECORD_DATA, 1, ref m_Data, 0, 0);
				if(Ret != 0)
				{
					string ErrorString;
					dig.GetErrorString(Ret, out ErrorString);
					textBoxInfo.Text = "dig.ReadLatestRecordss = " + Ret.ToString() + " : " + ErrorString;
					return;
				}
				//------------------------------------
				// Draw graph
				//------------------------------------
				DrawGraph();
			}
		}

		/// <summary>
		/// Show information
		/// </summary>
		private void buttonInfo_Click(object sender, System.EventArgs e)
		{
			int		Ret;		// Return value
			float	SampleRate;	// Sample rate
			float	Duty;		// Duty ratio
			float	Level;		// Trigger level
			short	Slope;		// Trigger direction
			int		Count;		// Trigger count
			int		Status;		// Status
			string	Str = "";

			//---------------------------------
			// Get the operation status
			//---------------------------------
			Ret = dig.GetStatus(m_Id, out Status);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetStatus = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			labelStatus.Text = Status.ToString("X") + "H";

			//-------------------------------------------
			// Display the device information
			//-------------------------------------------
			//---------------------------------
			// Get the sample rate
			//---------------------------------
			Ret = dig.GetSampleRate(m_Id, out SampleRate);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetSampleRate = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			Str = String.Format("Sample rate : {0:F3}Hz\r\n", SampleRate);
			//---------------------------------
			// Get the record length
			//---------------------------------
			Ret = dig.GetRecordLength(m_Id, out m_RecordLength);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetRecordLength = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			Str = Str + String.Format("Record length : {0:D}\r\n", m_RecordLength);
			//---------------------------------
			// Get duty ratio
			//---------------------------------
			Ret = dig.GetDutyCycle(m_Id, out Duty);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetRecordLength = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			Str = Str + String.Format("Duty ratio : {0:F3}%\r\n", Duty);
			//---------------------------------
			// Get the number of effective channels
			//---------------------------------
			Ret = dig.GetChannels(m_Id, out m_Channels);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetChannels = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			Str = Str + String.Format("Number of effective channels : {0:D}\r\n", m_Channels);
			//---------------------------------
			// Get the trigger information
			//---------------------------------
			Ret = dig.GetPostTriggerAiEdge(m_Id, out m_TriggerChannel, out Level, out Slope, out Count);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetPostTriggerAiEdge = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			Str = Str + String.Format("Trigger channel : {0:D}\r\n", m_TriggerChannel);
			Str = Str + String.Format("Trigger level : {0:F3}V\r\n", Level);
			//---------------------------------
			// Get the range information
			//---------------------------------
			Ret = dig.GetRange(m_Id, m_TriggerChannel, out m_Range);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.GetRange = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			Str = Str + String.Format("Input range : {0:F3}VPP\r\n", m_Range);
			//---------------------------------
			// Show the information
			//---------------------------------
			textBoxDeviceInfo.Text = Str;

			textBoxInfo.Text = "Show information : Normality completion";		
		}

		/// <summary>
		/// Stop acquisition
		/// </summary>
		private void buttonStop_Click(object sender, System.EventArgs e)
		{
			int		Ret;		// Return value
			Ret = dig.Stop(m_Id);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.Stop = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			textBoxInfo.Text = "Stop acquisition : Normality completion";		
		}

		/// <summary>
		/// Exit handling
		/// </summary>
		private void buttonExit_Click(object sender, System.EventArgs e)
		{
			int		Ret;	// Return value
			Ret = dig.Exit(m_Id);
			if(Ret != 0)
			{
				string ErrorString;
				dig.GetErrorString(Ret, out ErrorString);
				textBoxInfo.Text = "dig.Exit = " + Ret.ToString() + " : " + ErrorString;
				return;
			}
			textBoxInfo.Text = "Exit : Normality completion";		
		}

		/// <summary>
		/// Close Form
		/// </summary>
		private void Form1_Closed(object sender, System.EventArgs e)
		{
			// Exit handling
			dig.Exit(m_Id);		
		}

		/// <summary>
		/// Draw graph
		/// </summary>
		private void DrawGraph()
		{
			float XUnit;	// Drawing unit of X axis
			float PosX;		// Drawing coordinate of X axis
			float PosY;		// Drawing coordinate of Y axis
			float OldX;		// For saving the drawing coordinate of X axis
			float OldY;		// For saving the drawing coordinate of Y axis
			Pen pen;		// Pen

			// Draw the current data in graph
			Graph.Image = bmp;
			Graphics grp = Graphics.FromImage(Graph.Image);					// Creat a new graphics object from the specified image object
			grp.Clear(Graph.BackColor);										// Clear the graph

			//----------------------------------------------------
			// Repeat the drawing handling only for the times which is equal to the number of channels
			//----------------------------------------------------
			for(int i = 0; i < m_Channels; i++)
			{
				//----------------------------------------------------
				// Repeat the drawing handling only for the times which is equal to the numer of acquisition data
				//----------------------------------------------------
				if(i == 0)
				{
					pen = new Pen(System.Drawing.Color.Red, 1);		// Red
				}
				else
				{
					pen = new Pen(System.Drawing.Color.Blue, 1);		// Blue
				}
				XUnit = Graph.Size.Width / (float)(m_RecordLength);				// Calculate the moving pixel number of X axis for data 1
				OldY = Graph.Height * ((m_Range / 2) - m_Data[i]) / m_Range;	// Calculate the coordinate of Y axis
				// If the initial value of Y axis exceeds the drawing rect of graph
				if(OldY >= Graph.Height)
				{
					OldY = Graph.Height - 1;			// modify the drawing position
				}
				// If the coordinate of Y axis is lower than the drawing rect
				else if(OldY < 0)
				{
					OldY = 0;							// modify the drawing position
				}
				OldX = 0;
				for(int j = i ; j < m_RecordLength * m_Channels; j += m_Channels)
				{
					PosX = OldX + XUnit;	// Calculate the coordinate of X axis
					PosY = Graph.Height * ((m_Range / 2) - m_Data[j]) / m_Range;	// Calculate the coordinate of Y axis
					// If the coordinate of Y axis exceeds the drawing rect
					if(PosY >= Graph.Height)
					{
						PosY = Graph.Height - 1;		// Modify the drawing position
					}
					// If the coordinate of Y axis is lower than the drawing rect
					else if(PosY < 0)
					{
						PosY = 0;								// Modify the drawing position
					}
					grp.DrawLine(pen, OldX, OldY, PosX, PosY);	// Draw

					OldX = PosX;			// Save the drawing coordinate of X axis
					OldY = PosY;			// Save the drawing coordinate of Y axis
				}
				pen.Dispose();	// Reales all resoures used by this pen object
			}
			grp.Dispose();	// Reales all resoures used by this graphics object
		}
	}
}
