using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using OBD;

namespace OBD_PCScanner
{
	public partial class LampsForm : Form
	{
		public HOBD OBD = null;
		public bool NeedUpdate = false;
		private readonly ulong[] EnumValues;		
		public LampsForm()
		{
			InitializeComponent();
			Array ar = Enum.GetValues(typeof (HOBDFlags));
			EnumValues = new ulong[ar.Length];
			for (int i = 0; i < ar.Length; i++)
				EnumValues[i] = (ulong)(HOBDFlags)ar.GetValue(i);
		}

		private void timer_Tick(object sender, EventArgs e)
		{
			UpdateLamps();
		}

		private void UpdateLamps()
		{
			if (OBD == null)
				return;
			if (NeedUpdate || (OBD.Status.ChStateFlag & ChangeStateFlag.NewFlags) != 0)
				UpdateFlagsLamps();
		}
		private void UpdateFlagsLamps()
		{
			NeedUpdate = false;
			FGridFlagsLamps.Refresh();			
		}
		private void FGridFlagsLamps_OnGetCellInfo(PostWin.FastCell FastCell, object sender)
		{
			if(FastCell == null)
				return;
			int col = FastCell.Col;
			int row = FastCell.Row;
			FastCell.Text = "";
			if(row == 0)
			{
				if (col != 0)
					FastCell.Text = "b:" + (col - 1);
			}
			else
			if(col == 0)
			{
				FastCell.Text = string.Format("F{0} {1}", row, (row+7).ToString("X2"));
			}
			else
				if(OBD != null)
				{
					byte offset =(byte) (((row - 1) * 8) + (col - 1));
					ulong value = (ulong)((ulong) 1 << offset);
					bool defined = (((ulong)HOBDFlags.AllOn & value) != 0);
					//for(int i=0; i<EnumValues.Length; i++)
					//if(EnumValues[i] == value)
					//{
					//	defined = true;
					//	break;
					//}
					if(defined)
					{
						int i = 0;
					}
					FastCell.Text = defined ? ((HOBDFlags) value).ToString() : "";
					if (((ulong)OBD.Status.Flags & value) != 0)
						FastCell.BackColor = Color.Green;
					else
						FastCell.BackColor = Color.LightGray;
				}
		}

		private void LampsForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			if (e.CloseReason == CloseReason.UserClosing)
			{
				e.Cancel = true;
				Hide();
			}
		}
	}
}
