using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using CustomFormsPDA;
using OBD;
using PostWin;
using Steema.TeeChart.Pocket;
using ThreadSafe;

namespace OBD_PDAScanner
{
	public partial class MainFormPDAScanner : Form
	{
		private PWChart Chart;
		private LogEventList EventList;
		private HOBD OBD;
		private Steema.TeeChart.Styles.Line LineSeries;
		private readonly string ProgramDir;
		private LogStorage Log = new LogStorage();
		private NotifyForm NF;

		public MainFormPDAScanner()
		{
			InitializeComponent();
			InitChart();
			ProgramDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\";
			EventList = new LogEventList();
			OBD = new HOBD(ProgramDir) {Log = Log};
		}

		#region Controls Click Routines
		private void ExitItem_Click(object sender, EventArgs e)
		{
			Close();
		}
		private void PortUpDown_ValueChanged(object sender, EventArgs e)
		{
			OBD.Params.PortNumber = (int)PortUpDown.Value;
		}
		private void ConnectBtn_Click(object sender, EventArgs e)
		{
			if (OBD.Status.State == HOBDState.Disconnected)
				Connect();
			else
				Disconnect();
		}
		#endregion

		private void Connect()
		{
			OBD.Connect();
		}
		private void Disconnect()
		{
			OBD.Disconnect();
		}

		private void timer_Tick(object sender, EventArgs e)
		{
			if(OBD.Status.State != HOBDState.Disconnected)
			{
				string s = OBD.FatalError;
				if (!string.IsNullOrEmpty(s))
				{
					NF.Show(s, EventType.Error);
					Disconnect();
				}
			}
			UpdateButtons();
			UpdateLog();
			//UpdateSeries();
		}

		private void UpdateButtons()
		{
			string s = OBD.Status.StateStr;
			if (StatusLbl.Text != s)
				StatusLbl.Text = s;
			bool b = OBD.Status.State != HOBDState.Connecting;
			if (ConnectBtn.Enabled != b)
				ConnectBtn.Enabled = b;
			b = OBD.Status.State == HOBDState.Disconnected;
			if (PortUpDown.Enabled != b)
				PortUpDown.Enabled = b;
		}


		#region Charts Routines
		private Random r = new Random();
		private void UpdateSeries()
		{
			LineSeries.BeginUpdate();
			LineSeries.Clear();

			double[] tmp = new double[100];
			for (int i = 0; i < tmp.Length; i++)
				tmp[i] = r.NextDouble()*2-1;
			for (int i = 0; i < tmp.Length; i++)
			{
				//LineSeries.FillSampleValues(r.Next(100) + 50);
				LineSeries.Add(tmp[i], Color.Yellow);
			}
			LineSeries.EndUpdate();
			LineSeries.Repaint();
			//Chart.Refresh();
		}

		private void InitChart()
		{
			Chart = new PWChart();
			LineSeries = new Steema.TeeChart.Styles.Line(Chart.Chart);
			LineSeries.ColorEach = false;
			//LineSeries..Visible = false;
			LineSeries.Color = Color.Yellow;
			//LineSeries.AreaLines = new Pen(Color.Yellow);
			//LineSeries.IgnoreNulls = true;
			Chart.Location = new System.Drawing.Point(0, 0);
			Chart.Series.Add(LineSeries);
			Chart.Axes.Left.Labels.Font.Size = 6;
			Chart.Axes.Bottom.Labels.Font.Size = 6;
			Chart.Size = new System.Drawing.Size(224, 168);
			Chart.Dock = DockStyle.Fill;
			LineSeries.Marks.Visible = false;
			Chart.Aspect.View3D = false;
			Chart.Axes.Left.Title.Visible = false;
			Chart.Axes.Bottom.Labels.Style = Steema.TeeChart.AxisLabelStyle.Auto;
			//Chart.Axes.Bottom.SetMinMax(0,100);
			LineSeries.ColorEach = true;
			Chart.Panel.MarginLeft = 0;
			Chart.Panel.MarginBottom = 0;
			//Chart.Axes.Left.SetMinMax(10, 100);
			Chart.GetAxisLabel += new GetAxisLabelEventHandler(Chart_GetAxisLabel);
			ChartPanel.Controls.Add(Chart);

			Chart.Legend.Visible = false;
			Chart.Panel.Color = Color.Gray;
			Chart.Header.Text = "Кол-во в мин";
			Chart.Header.Visible = false;
		}
		void Chart_GetAxisLabel(object sender, GetAxisLabelEventArgs e)
		{
			if (sender == Chart.Axes.Bottom)
			{
				try
				{
					//int Seconds = (int)VBS.WorkingTime.TotalSeconds;
					//int s = Seconds - RegsHistory.Count + (int)(double.Parse(e.LabelText));
					//if (s < 0) s = 0;
					//TimeSpan ts = TimeSpan.FromSeconds(s);
					//e.LabelText = ((int)(ts.TotalMinutes)).ToString("00") + ":" + ts.Seconds.ToString("00");
				}
				catch
				{
					e.LabelText = "";
				}
			}
		}
		#endregion

		#region Log List Routines
		private void EventsGrid_OnGetCellInfo(FastCell FastCell)
		{
			FastCell.FontStyle = FontStyle.Regular;
			if (FastCell.Row == 0)
			{
				FastCell.Aligment = Aligment.Center;
				switch (FastCell.Col)
				{
					case 0:
						FastCell.Text = "Время";
						break;
					case 1:
						FastCell.Text = "Событие";
						break;
				}
			}
			else
			{
				FastCell.Aligment = Aligment.Left;
				FastCell.BackColor = EventsGrid.BackColor;
				FastCell.ForeColor = EventsGrid.ForeColor;
				int Index = FastCell.Row - 1;
				if (Index < EventList.Count)
				{
					LogEventList.LogEvent E = EventList[Index];
					string txt = FastCell.Col < E.LogStrings.Length ? E.LogStrings[FastCell.Col] : "";
					FastCell.ForeColor = E.LogColor;
					FastCell.FontStyle = E.Style;
					FastCell.Text = txt;
				}
				else FastCell.Text = "";
			}
		}

		private void UpdateLog()
		{
			bool Updated = false;
			while (Log.LogCount > 0)
			{
				EventList.AddRecord(Log.LogItems);
				Updated = true;
			}
			if (Updated)
				UpdateEventGrid();
		}
		private void UpdateEventGrid()
		{
			if (EventsGrid.RowCount != EventList.Count + 1)
			{
				EventsGrid.RowCount = EventList.Count + 1;
			}
			else
				EventsGrid.Refresh();
		}

		#endregion

		#region Load Save
		private void MainForm_Load(object sender, EventArgs e)
		{
			OBD.Load();
			NF = new NotifyForm(EventImageList);
			PortUpDown.Value = OBD.Params.PortNumber;
			//if(OBD.SensorsHistory != null)
		}

		private void MainForm_Closing(object sender, CancelEventArgs e)
		{
			OBD.Save();
		}

		#endregion
	}
	#region PWChart
	public class PWChart : TChart
	{
		Bitmap bmp;
		Graphics g;
		private void CreateBMP()
		{
			if (bmp != null)
				bmp.Dispose();
			if (g != null)
				bmp.Dispose();
			bmp = new Bitmap(this.Width, this.Height);
			g = Graphics.FromImage(bmp);
		}

		protected override void OnResize(EventArgs e)
		{
			//CreateBMP();
			base.OnResize(e);
		}

		protected override void OnPaint(PaintEventArgs e)
		{
			try
			{
				if (g == null)
					CreateBMP();
				g.Clear(BackColor);
				PaintEventArgs arg = new PaintEventArgs(g, e.ClipRectangle);
				Graphics oldg = e.Graphics;
				base.OnPaint(arg);
				oldg.DrawImage(bmp, 0, 0);
				GC.SuppressFinalize(arg);
				arg = null;
			}
			catch { }
		}
	}
	#endregion

}