using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Collections;
using System.IO;


namespace EQTrack
{
    public partial class MainMenuForm : Form
    {

        #region set variables
        private DateTime TestStarted = new DateTime();
        private TimeSpan timeLeft = new TimeSpan();
        //private string FirstConnectFunctionNumber = "1f";
        //        private string FirstConnectFunctionNumber = "1";
        private bool testing = false;
        ContextMenu menuUnitButton = new ContextMenu();
        Form progress;



        int length = 6;
        int counter = 0;
        string input = "";
        Hashtable htControls = new Hashtable();
        Hashtable htBlackhawks = new Hashtable();
        Hashtable htErorr = new Hashtable();
        Hashtable htValid = new Hashtable();
        Hashtable htMapping = new Hashtable();
        Hashtable htPassed = new Hashtable();

        CustomButton currentfocus;
        Color scannedColor = Color.Gray;
        string strFilePath = "./BH PRODUCTION TEMPLATE.xls";
        Color currentButtonColor = Color.White;
        Color flashColor = Color.Blue;


        //Variable used to test the blackhawks
        //       double factory_Latitude = -36.74787; //http://pagesperso-orange.fr/universimmedia/geo/loc.htm
        //      double factory_Longitude = 174.70532; //2 Piermark Dr North Harbour, 0632 New Zealand
        //     double errorRange = 10;

        #endregion

        public MainMenuForm()
        {
            InitializeComponent();
            #region put blackhawk buttons into a hashtable
            htControls.Add(1, unitButton1);
            htControls.Add(2, unitButton2);
            htControls.Add(3, unitButton3);
            htControls.Add(4, unitButton4);
            htControls.Add(5, unitButton5);
            htControls.Add(6, unitButton6);
            htControls.Add(7, unitButton7);
            htControls.Add(8, unitButton8);
            htControls.Add(9, unitButton9);
            htControls.Add(10, unitButton10);
            htControls.Add(11, unitButton11);
            htControls.Add(12, unitButton12);
            htControls.Add(13, unitButton13);
            htControls.Add(14, unitButton14);
            htControls.Add(15, unitButton15);
            htControls.Add(16, unitButton16);
            htControls.Add(17, unitButton17);
            htControls.Add(18, unitButton18);
            htControls.Add(19, unitButton19);
            htControls.Add(20, unitButton20);
            htControls.Add(21, unitButton21);
            htControls.Add(22, unitButton22);
            htControls.Add(23, unitButton23);
            htControls.Add(24, unitButton24);
            htControls.Add(25, unitButton25);
            htControls.Add(26, unitButton26);
            htControls.Add(27, unitButton27);
            htControls.Add(28, unitButton28);
            htControls.Add(29, unitButton29);
            htControls.Add(30, unitButton30);
            htControls.Add(31, unitButton31);
            htControls.Add(32, unitButton32);
            htControls.Add(33, unitButton33);
            htControls.Add(34, unitButton34);
            htControls.Add(35, unitButton35);
            htControls.Add(36, unitButton36);
            htControls.Add(37, unitButton37);
            htControls.Add(38, unitButton38);
            htControls.Add(39, unitButton39);
            htControls.Add(40, unitButton40);
            htControls.Add(41, unitButton41);
            htControls.Add(42, unitButton42);
            htControls.Add(43, unitButton43);
            htControls.Add(44, unitButton44);
            htControls.Add(45, unitButton45);
            htControls.Add(46, unitButton46);
            htControls.Add(47, unitButton47);
            htControls.Add(48, unitButton48);
            htControls.Add(49, unitButton49);
            htControls.Add(50, unitButton50);
            htControls.Add(51, unitButton51);
            htControls.Add(52, unitButton52);
            htControls.Add(53, unitButton53);
            htControls.Add(54, unitButton54);
            #endregion
            SetButtonLocation(Layer1.Width, Layer1.Height);

            MenuItem menuItemDelete = new MenuItem("Delete (&D)");
            menuItemDelete.Click += new EventHandler(menuItemDelete_Click);
            menuUnitButton.MenuItems.Add(menuItemDelete);

            #region initialise the errors, blackhawks
            for (int i = 1; i <= htControls.Count; i++)
            {
                htBlackhawks.Add(i, "None");
                htErorr.Add(i, "Errors(if any):");
                htValid.Add(i, 0);
                htPassed.Add(i, 0);
                ((CustomButton)htControls[i]).ContextMenu = menuUnitButton;
            }
            #endregion



            Globals.EventService.GetEventsForCustomerCompleted += new EQTrack.BlackhawkEventService.GetEventsForCustomerCompletedEventHandler(EventService_GetEventsForCustomerCompleted);
            unitButton1.Focus();
            //   unitButton1.BorderStyle = BorderStyle.FixedSingle;

            currentfocus = unitButton1;
            #region set timer for button flashing
            System.Timers.Timer t = new System.Timers.Timer(300);
            t.Elapsed += new System.Timers.ElapsedEventHandler(theout);
            t.AutoReset = true;
            t.Enabled = true;
            // unitButton1.PanelColor = Color.Blue;
            //    MessageBox.Show(unitButton1.InvokeRequired.ToString());
            #endregion

        }
        #region set button focus
        public void setFocus()
        {
            currentfocus.Focus();
        }
        #endregion
        #region Timmer event
        public void theout(object source, System.Timers.ElapsedEventArgs e)
        {

            //Console.WriteLine("time is going");
            //  MessageBox.Show(unitButton1.InvokeRequired.ToString());
            try
            {
                currentfocus.Invoke(new MethodInvoker(ButtonColorToggle));
            }
            catch (Exception)
            {
            }



        }
        #endregion
        #region Toggle the current button color
        private void ButtonColorToggle()
        {
            //  currentfocus.PanelColorHover = Color.Transparent;
            // setFocus();
            if (!testing)
            {
                if (currentfocus.Focused == true)
                {
                    if (currentfocus.PanelColor != flashColor)
                    {
                        currentfocus.PanelColor = flashColor;
                    }
                    else
                    {
                        currentfocus.PanelColor = currentButtonColor;
                    }
                }
                else
                {
                    if (currentButtonColor != currentfocus.PanelColor)
                    {
                        currentfocus.PanelColor = currentButtonColor;
                    }
                }
            }
        }
        #endregion
        #region Set the button location
        private void SetButtonLocation(int layerWidth, int layerHeight)
        {
            int unitWidth = ((CustomButton)htControls[1]).Width;
            unitWidth = layerWidth * 4 / 5 / 6;
            int unitHeight = ((CustomButton)htControls[1]).Height;
            unitHeight = layerHeight * 4 / 5 / 3;
            int xMargin = (layerWidth - unitWidth * 6) / 5;
            //xMargin = 0;
            int yMargin = (layerHeight - unitHeight * 3) / 2;

            //yMargin = 0;
            for (int i = 0; i < 54; i++)
            {
                ((CustomButton)htControls[i + 1]).SetBounds((unitWidth + xMargin) * (i % 18 % 6), (unitHeight + yMargin) * (i % 18 / 6), unitWidth, unitHeight);
            }
        }
        #endregion
        #region log out
        private void LogoutButton_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(Globals.MainForm, "Are you sure you want to Log Out?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                Globals.MainForm.AnimateDirectionLeft = false;
                Globals.MainForm.CurrentPanel = Globals.LoginForm.MainPanel;
            }
        }
        #endregion
        private List<Globals.BlackhawkEventItem> EventList = new List<Globals.BlackhawkEventItem>();
        private void EventService_GetEventsForCustomerCompleted(object sender, EQTrack.BlackhawkEventService.GetEventsForCustomerCompletedEventArgs e)
        {
            if (!e.Cancelled && e.Error == null)
            {
                if (e.Result != null)
                {


                }

            }
        }

        private void menuItemDelete_Click(object sender, EventArgs e)
        {
            // string name = menuUnitButton.SourceControl.Name;
            //MessageBox.Show(name);

            if (testing)
            {
                MessageBox.Show("Testing is in progress");
            }
            else
            {


                int htIndex = Int16.Parse(((CustomButton)menuUnitButton.SourceControl).Name.Substring(10));

                htErorr[htIndex] = "Errors(if any):";
                htPassed[htIndex] = 0;
                ((CustomButton)htControls[htIndex]).PanelColor = Color.White;
                htValid[htIndex] = 0;
                if (currentfocus == ((CustomButton)htControls[htIndex]))
                {
                    currentButtonColor = Color.White;
                }
                htBlackhawks[htIndex] = "None";
                ((CustomButton)htControls[htIndex]).Caption = "";

            }



        }


        private void EditExistingCustomerButton_Click(object sender, EventArgs e)
        {
            Globals.MainForm.AnimateDirectionLeft = true;
            //Globals.MainForm.CurrentPanel = Globals.EditCustomerForm.MainPanel;
            //Globals.EditCustomerForm.RefreshCompanies();  
        }

        private void CompanyButton_Click(object sender, EventArgs e)
        {
            Globals.MainForm.AnimateDirectionLeft = true;
            //Globals.MainForm.CurrentPanel = Globals.SelectDeviceForm.MainPanel;
            try
            {
                System.Data.DataSet dsCompanies = Globals.AdminService.GetCompanies("");
                //Globals.SelectDeviceForm.fillCompanies(dsCompanies);
            }
            catch (Exception err)
            {
                if (err.Message.ToString() == "No access rights to this method")
                {
                    string DeviceName = "Device Set";
                    int DeviceSetID = Globals.AdminService.GetDeviceSetID(Globals.LoginForm.CurrentUserName);
                    int CompanyID = Globals.AdminService.GetCompany();
                    System.Data.DataSet dsCompanies = new DataSet();
                    dsCompanies.Tables.Add();

                    dsCompanies.Tables[0].Columns.Add("CompanyID");
                    dsCompanies.Tables[0].Columns.Add("Device Set Name");
                    dsCompanies.Tables[0].Columns.Add("unknown");
                    dsCompanies.Tables[0].Columns.Add("DeviceSetID");
                    dsCompanies.Tables[0].Rows.Add(new string[] { "", DeviceName, "", DeviceSetID.ToString() });

                    //Globals.SelectDeviceForm.fillCompanies(dsCompanies);
                }
            }


        }

        private void AssignDevicestoCustomerButton_Click(object sender, EventArgs e)
        {
            Globals.MainForm.AnimateDirectionLeft = true;
            //Globals.MainForm.CurrentPanel = Globals.EditDevicesForm.MainPanel;
            //Globals.EditDevicesForm.RefreshDevices();
        }

        private void RunTestButton_Click(object sender, EventArgs e)
        {
            if (testing)
            {
                testing = false;
                flashColor = Color.Blue;
                RunTestButton.Caption = "Test";

                btnClear.Enabled = true;
                btnDone.Enabled = true;
                btnOptions.Enabled = true;
                LogoutButton.Enabled = true;
                Excel2CSV.Enabled = true;

                int iAmountofDevices = DevicesGridView.Rows.Count;
                for (int iIndex = 0; iIndex <= iAmountofDevices - 1; iIndex++)
                {
                    int htIndex = 0;
                    htIndex = int.Parse(htMapping[iIndex].ToString());
                    if (htPassed[htIndex].ToString() == "0")
                    {
                        htPassed[htIndex] = "3";
                        if (currentfocus == (CustomButton)htControls[htIndex])
                        {
                            currentButtonColor = Color.Red;
                        }
                        ((CustomButton)htControls[htIndex]).PanelColor = Color.Red;
                    }

                }
                Application.DoEvents();
                StopWatchtimer.Stop();
                CheckEventsTimer.Stop();
            }
            else
            {
                testing = true;
                currentfocus.PanelColor = currentButtonColor;
                RunTestButton.Caption = "Stop";

                btnClear.Enabled = false;
                btnDone.Enabled = false;
                btnOptions.Enabled = false;
                LogoutButton.Enabled = false;
                Excel2CSV.Enabled = false;
                PopulateTest();
                int iAmountofDevices = DevicesGridView.Rows.Count;
                for (int iIndex = 0; iIndex <= iAmountofDevices - 1; iIndex++)
                {
                    DevicesGridView.Rows[iIndex].Cells["FirstConnectColumn"].Value = Properties.Resources.None;
                    DevicesGridView.Rows[iIndex].Cells["GPSColumn"].Value = Properties.Resources.None;
                    DevicesGridView.Rows[iIndex].Cells["GSMColumn"].Value = Properties.Resources.None;
                    DevicesGridView.Rows[iIndex].Cells["SWVColumn"].Value = Properties.Resources.None;
                    DevicesGridView.Rows[iIndex].Cells["ConfigColumn"].Value = Properties.Resources.None;
                }
                TestStarted = DateTime.Now;
                timeLeft = TestStarted - DateTime.Now;
                TestTimeLabel.Text = (DateTime.Now - TestStarted).ToString();
                CheckEventsTimer.Start();
                StopWatchtimer.Start();
            }
        }

        public void PopulateTest()
        {
            //  DataTable DT = Globals.DeviceSetService.GetDevicesForDeviceSet(Globals.CustomerID);
            DevicesGridView.Rows.Clear();
            flashColor = Color.Magenta;
            int count = 0;
            // int iAmountofDevices = DT.Rows.Count;
            htMapping.Clear();
            for (int iIndex = 1; iIndex <= htControls.Count; iIndex++)
            {
                //               DevicesGridView.Rows.Add(DT.Rows[iIndex]["SEN"].ToString());
                if (htValid[iIndex].ToString() == "1")
                {
                    if (htPassed[iIndex].ToString() != "1")
                    {
                        htPassed[iIndex] = "0";
                        if (((CustomButton)htControls[iIndex]).Focused)
                        {
                            currentButtonColor = scannedColor;
                        }
                        ((CustomButton)htControls[iIndex]).PanelColor = scannedColor;
                        DevicesGridView.Rows.Add(htBlackhawks[iIndex].ToString());
                        htMapping.Add(count, iIndex);
                        count++;
                    }

                }

            }
        }

        private void CheckEventsTimer_Tick(object sender, EventArgs e)
        {

            string LatestSoftwareVersion = Globals.htOptions["SWV"].ToString();
            int GSMPassSignalLevel = int.Parse(Globals.htOptions["Min_SSI"].ToString());
            TestTimeLabel.ForeColor = Color.Red;
            int iAmountofDevices = DevicesGridView.Rows.Count;
            for (int iIndex = 0; iIndex <= iAmountofDevices - 1; iIndex++)
            {
                bool allPass = true;
                int htIndex = 0;
                htIndex = Int32.Parse(htMapping[iIndex].ToString());
                string deviceID = DevicesGridView.Rows[iIndex].Cells["SerialNumberColumn"].Value.ToString();
                if (htPassed[htIndex].ToString() != "1")
                {
                    htErorr[htIndex] = "Errors(if any):";

                    StopWatchtimer_Tick(null, null);
                    Application.DoEvents();
                    DataTable DT = new DataTable();
                    DT = Globals.DeviceService.GetDeviceStatus(deviceID);
                    if (DT.Rows.Count > 0)
                    {
                        if (DT.Rows[0]["LastHeartbeat"].ToString() != "")
                        {
                            if ((DateTime)DT.Rows[0]["LastHeartbeat"] >= TestStarted)
                            {
                                DevicesGridView.Rows[iIndex].Cells["FirstConnectColumn"].Value = Properties.Resources.Marginal;
                            }
                        }
                        //if the status has been updated after the test has been started and the last function is a 1.
                        //     MessageBox.Show((DT.Rows[0]["Date_Recorded"].ToString() == "").ToString());
                        //((DT.Rows[0]["Date_Recorded"].ToString() == "")|(DateTime)DT.Rows[0]["Date_Recorded"] >= TestStarted) & 
                        bool rightDate = false;
                        if (DT.Rows[0]["Date_Recorded"].ToString() == "")
                        {
                            //rightDate = true;
                        }
                        else if ((DateTime)DT.Rows[0]["Date_Recorded"] >= TestStarted)
                        {
                            rightDate = true;
                        }
                        rightDate = true;

                        //  MessageBox.Show((DT.Rows[0]["FUN"].ToString() == FirstConnectFunctionNumber).ToString());

                        //     MessageBox.Show(DT.Rows[0]["FUN"].ToString());
                        //   MessageBox.Show(FirstConnectFunctionNumber);

                        if (rightDate & (DT.Rows[0]["FUN"].ToString() == Globals.htOptions["FUN"].ToString()))
                        {


                            DevicesGridView.Rows[iIndex].Cells["FirstConnectColumn"].Value = Properties.Resources.Passed;
                            // If there is a good GPS fix and the Lat and LOn num2str(values are updated. 
                            double numLat = Double.Parse(DT.Rows[0]["Dec_LAT"].ToString());
                            double numLon = Double.Parse(DT.Rows[0]["Dec_Lon"].ToString());
                            if (Globals.htOptions["Min_LAT"].ToString() != "" &&
                                Globals.htOptions["Max_LAT"].ToString() != "" &&
                                Globals.htOptions["Min_LON"].ToString() != "" &&
                                Globals.htOptions["Max_LON"].ToString() != "")
                            {

                                double min_factory_Latitude = Double.Parse(Globals.htOptions["Min_LAT"].ToString());
                                double max_factory_Latitude = Double.Parse(Globals.htOptions["Max_LAT"].ToString());
                                double min_factory_Longitude = Double.Parse(Globals.htOptions["Min_LON"].ToString());
                                double max_factory_Longitude = Double.Parse(Globals.htOptions["Max_LON"].ToString());
                                if ((int.Parse(DT.Rows[0]["FIX"].ToString().Trim()) == int.Parse(Globals.htOptions["Min_FIX"].ToString())) && (numLat < max_factory_Latitude
                                    && numLat > min_factory_Latitude) && (numLon < max_factory_Longitude
                                    && numLon > min_factory_Longitude))
                                {
                                    DevicesGridView.Rows[iIndex].Cells["GPSColumn"].Value = Properties.Resources.Passed;
                                }
                                else
                                {
                                    DevicesGridView.Rows[iIndex].Cells["GPSColumn"].Value = Properties.Resources.Failed;
                                    allPass = false;
                                    htErorr[htIndex] += "\nGPS failed";


                                }
                            }

                            // if the GSM SSI is greater than 19.
                            if ((int.Parse(DT.Rows[0]["SSI"].ToString().Trim()) >= int.Parse(Globals.htOptions["Min_SSI"].ToString())))
                            {
                                DevicesGridView.Rows[iIndex].Cells["GSMColumn"].Value = Properties.Resources.Passed;
                            }
                            else
                            {
                                DevicesGridView.Rows[iIndex].Cells["GSMColumn"].Value = Properties.Resources.Failed;
                                allPass = false;
                                htErorr[htIndex] += "\nGSM failed";
                            }

                            // if the Software Version is correct.
                            if ((DT.Rows[0]["SWV"].ToString() == Globals.htOptions["SWV"].ToString()))
                            {
                                DevicesGridView.Rows[iIndex].Cells["SWVColumn"].Value = Properties.Resources.Passed;
                            }
                            else
                            {
                                DevicesGridView.Rows[iIndex].Cells["SWVColumn"].Value = Properties.Resources.Failed;
                                allPass = false;
                                htErorr[htIndex] += "\nSWV failed";
                            }

                            //DataTable dtEvents = Globals.EventService.GetEventsForDevice(deviceID, "21/Mar/2008", 1);
                            // if (dtEvents.Rows.Count != 0)
                            //{
                            double battery_level = double.Parse(DT.Rows[0]["BAT"].ToString());
                            double min_bettery_level = double.Parse(Globals.htOptions["Min_Battery"].ToString());
                            double max_bettery_level = double.Parse(Globals.htOptions["Max_Battery"].ToString());
                            if (battery_level >= min_bettery_level && battery_level <= max_bettery_level)
                            {

                            }
                            else
                            {
                                allPass = false;
                                htErorr[htIndex] += "\nBattery failed";
                            }


                            //}
                            //else
                            //{
                            //   allPass = false;
                            //  htErorr[htIndex] += "\nBattery failed";
                            //}



                            // if the serial Number is correct.
                            // need to look at all the other data here too.
                            //                        if ((DT.Rows[0]["SEN"].ToString() == DevicesGridView.Rows[iIndex].Cells["SerialNumberColumn"].Value.ToString()))
                            //                        {
                            //                            DevicesGridView.Rows[iIndex].Cells["ConfigColumn"].Value = Properties.Resources.Passed;
                            //                        }
                            //                        else
                            //                        {
                            //                            DevicesGridView.Rows[iIndex].Cells["ConfigColumn"].Value = Properties.Resources.Failed;
                            //                            allPass = false;
                            //                            htErorr[htIndex] += "\nConfig failed";
                            //                        }

                            if (allPass)
                            {
                                htPassed[htIndex] = "1";
                                ((CustomButton)htControls[htIndex]).PanelColor = Color.Lime;
                                if (((CustomButton)htControls[htIndex]).Focused == true)
                                {
                                    currentButtonColor = Color.Lime;
                                }
                            }
                            else
                            {
                                ((CustomButton)htControls[htIndex]).PanelColor = Color.Orange;
                                if (((CustomButton)htControls[htIndex]).Focused == true)
                                {
                                    currentButtonColor = Color.Orange;
                                }
                            }


                        }
                    }
                }
            }
            TestTimeLabel.ForeColor = Color.White;
        }


        private void StopWatchtimer_Tick(object sender, EventArgs e)
        {

            timeLeft = (DateTime.Now - TestStarted);
            string tempTime = timeLeft.ToString();
            if (tempTime.IndexOf(".") != -1)
                tempTime = tempTime.Substring(0, tempTime.IndexOf('.'));
            TestTimeLabel.Text = tempTime;

        }

        private void DevicesGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            Globals.DeviceEventsForm.AddEvents(Globals.EventService.GetEventsForDevice(DevicesGridView.Rows[e.RowIndex].Cells["SerialNumberColumn"].Value.ToString(), "1 Jan 1970", 10));
            Globals.MainForm.AnimateDirectionLeft = true;
            Globals.MainForm.CurrentPanel = Globals.DeviceEventsForm.MainPanel;
        }

        private void DevicesGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DeviceStatusTable.DataSource = Globals.DeviceService.GetDeviceStatus(DevicesGridView.Rows[e.RowIndex].Cells["SerialNumberColumn"].Value.ToString());
            DeviceStatusTable.Columns["Enabled"].Visible = false;
            DeviceStatusTable.Columns["Date_First_Enabled"].Visible = false;
            DeviceStatusTable.Columns["TRI_Days"].Visible = false;
            DeviceStatusTable.Columns["TRI_Hours"].Visible = false;
            DeviceStatusTable.Columns["TRI_Minutes"].Visible = false;
            DeviceStatusTable.Columns["TRI_Seconds"].Visible = false;
            DeviceStatusTable.Columns["OSI"].Visible = false;
            DeviceStatusTable.Columns["Panic_Alert"].Visible = false;
            DeviceStatusTable.Columns["Alarm_Alert"].Visible = false;
            DeviceStatusTable.Columns["Lock_Door_Control"].Visible = false;
            DeviceStatusTable.Columns["Unlock_Door_Control"].Visible = false;
            DeviceStatusTable.Columns["Low_Battery_Indicator"].Visible = false;
            DeviceStatusTable.Columns["Disconnected_Battery_Indicator"].Visible = false;
            DeviceStatusTable.Columns["Crash_Sensor"].Visible = false;
            DeviceStatusTable.Columns["Low_Power_Mode"].Visible = false;
            DeviceStatusTable.Columns["Over_Speed_Indicator"].Visible = false;
            DeviceStatusTable.Columns["Immobilizer"].Visible = false;
            DeviceStatusTable.Columns["Ignition_Monitoring"].Visible = false;
            DeviceStatusTable.Columns["Heartbeatrate"].Visible = false;
        }
        #region wait for clean up
        private void insertBH_Click(object sender, EventArgs e)
        { }
        private void MainMenuForm_KeyPress(object sender, KeyPressEventArgs e)
        {

        }
        private void customButton1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {


        }
        private void customRoundPanel3_Click(object sender, EventArgs e)
        {
            //  Console.WriteLine("button_clicked");
        }
        private void customButton19_Click_1(object sender, EventArgs e)
        {

        }

        private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
        {

        }

        private void customRoundPanel3_Paint(object sender, PaintEventArgs e)
        {

        }
        #endregion


        #region check if the scanned blackhawks are valid
        private bool ValidInput(string input, int errorIndex)
        {
            bool valid = true;
            if (input.Length < length)
            {
                htErorr[errorIndex] += "\nSerial Number should be 6 digits.";
                return false;
            }
            else
            {
                #region Check if in the right format
                input = input.Substring(input.Length - length, length);
                bool foundMatch = false;
                string pattern = @"\d{" + length + @"}";
                try
                {
                    foundMatch = Regex.IsMatch(input, pattern);
                }
                catch (ArgumentException ex)
                {
                    // Syntax error in the regular expression
                    Console.WriteLine(ex);
                }
                //Console.WriteLine(foundMatch);
                #endregion

                if (foundMatch)
                {
                    #region Check if is already scaned

                    foreach (int key in htBlackhawks.Keys)
                    {
                        if (key != errorIndex)
                        {
                            if (htBlackhawks[key].ToString() == input)
                            {
                                //    if (key != errorIndex)
                                //   {

                                if (htValid[key].ToString() == "1")
                                {
                                    htErorr[errorIndex] += "\nAlready scaned, see Blackhawk " + key;

                                    //valid = false;
                                    return false;
                                    //break;
                                }
                            }
                            //  }

                        }

                    }
                    #endregion

                    if (valid == true)
                    {
                        if ((bool)Globals.htOptions["ChkFactoryDB"])
                        {
                            #region Check if in the factory database
                            try
                            {
                                System.Data.OleDb.OleDbConnection conn = getConn(); //getConn():
                                OleDbDataAdapter adapter = new OleDbDataAdapter();
                                string sqlstr = "select * from SerialNumbers where BHID = '" + input + "'";
                                // MessageBox.Show(input);

                                DataTable foundBH = new DataTable();
                                adapter.SelectCommand = new OleDbCommand(sqlstr, conn);
                                adapter.Fill(foundBH);
                                if (foundBH.Rows.Count < 1)
                                {
                                    valid = false;
                                    htErorr[errorIndex] += "\nBlackhawk is not in QC database";
                                }
                                else
                                {
                                    //    MessageBox.Show(foundBH.Rows[0]["ACTIVATION"].ToString().ToUpper());
                                    if (foundBH.Rows[0]["ACTIVATION"].ToString().ToUpper() != "TRUE")
                                    {
                                        valid = false;
                                        htErorr[errorIndex] += "\nBlackhawk is not activated";
                                    }
                                }


                                conn.Close();
                            }
                            catch (Exception e)
                            {
                                valid = false;
                                htErorr[errorIndex] += "\nError occured when connected to QC database";

                                MessageBox.Show("Error:" + e.Message);


                            }
                        }
                            #endregion
                        #region Check if in the blackhawk database

                        try
                        {
                            DataTable dt = new DataTable();
                            dt = Globals.DeviceService.GetDeviceStatus(input);
                            if (dt.Rows.Count < 1)
                            {
                                valid = false;
                                htErorr[errorIndex] += "\nBlackhawk is not in Blackhawk database";
                            }
                            else
                            {
                                //  MessageBox.Show(dt.Rows[0]["Enabled"].ToString());
                                if (dt.Rows[0]["Enabled"].ToString().ToUpper() != "TRUE")
                                {
                                    valid = false;
                                    htErorr[errorIndex] += "\nBlackhawk is not enabled";
                                }
                                //      MessageBox.Show(dt.Rows[0]["Customer ID"].ToString());


                            }
                        }
                        catch (Exception e)
                        {
                            valid = false;
                            htErorr[errorIndex] += "\nError occured when connected to Blackhawk server";
                            MessageBox.Show("Error" + e.Message);


                        }


                        #endregion

                    }
                }
                else
                {
                    htErorr[errorIndex] += "\nSerial Number is in wrong format";
                    return false;
                }



                return valid;
            }


        }
        #endregion
        #region get connection to the access file
        public OleDbConnection getConn()
        {
            string connstr = "Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=" + Globals.htOptions["Database"];
            OleDbConnection tempconn = new OleDbConnection(connstr);
            return (tempconn);
        }
        #endregion


        #region listen to the scanner and take input
        private void customButton1_PreviewKeyDown_1(object sender, PreviewKeyDownEventArgs e)
        {
            // Console.WriteLine("button");
            //Console.WriteLine((char)e.KeyValue);
            if (!testing)
            {
                if (e.KeyValue != 13)
                {
                    string tempValue = "";
                    if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                    {
                        tempValue += (char)e.KeyValue;
                    }
                    else
                    {
                        tempValue += (char)(e.KeyValue - (97 - 49));

                    }
                    input += tempValue;
                    counter++;
                }
                //            Console.WriteLine("Keypressed");

                if (e.KeyValue == 13)
                {

                    int htIndex = Int16.Parse(((CustomButton)sender).Name.Substring(10));

                    htErorr[htIndex] = "Errors(if any):";
                    if (counter == 0)
                    {
                        htErorr[htIndex] += "\nSerial number is empty";
                    }
                    if (ValidInput(input, htIndex))
                    {

                        //Console.WriteLine(output);

                        string output = input.Substring(input.Length - length, length);
                        htBlackhawks[htIndex] = output;
                        htValid[htIndex] = 1;
                        Console.WriteLine(htBlackhawks[htIndex]);

                        ((CustomButton)sender).PanelColor = scannedColor;
                        ((CustomButton)sender).Caption = output;
                        htPassed[htIndex] = 0;
                    }
                    else
                    {
                        htValid[htIndex] = 0;
                        htBlackhawks[htIndex] = input;
                        Console.WriteLine("invalid input");
                        ((CustomButton)sender).PanelColor = Color.Pink;
                        ((CustomButton)sender).Caption = input;
                    }
                    counter = 0;
                    input = "";

                    htIndex += 1;
                    Console.WriteLine(htIndex);
                    if (htIndex <= htControls.Count)
                    {
                        if (htIndex == 19)
                        {
                            Layers.SelectTab(1);

                        }
                        if (htIndex == 37)
                        {
                            Layers.SelectTab(2);

                        }
                        //     ((CustomButton)sender).BorderStyle = BorderStyle.None;
                        Console.WriteLine(((CustomButton)htControls[htIndex]).Name);
                        currentfocus.BorderStyle = BorderStyle.None;
                        ((CustomButton)htControls[htIndex]).Focus();
                        currentfocus = (CustomButton)htControls[htIndex];
                        currentButtonColor = currentfocus.PanelColor;
                        //   ((CustomButton)htControls[htIndex]).BorderStyle = BorderStyle.FixedSingle;


                    }
                    else
                    {
                        Layers.SelectTab(0);
                        currentfocus.BorderStyle = BorderStyle.None;
                        ((CustomButton)htControls[1]).Focus();
                        currentfocus = (CustomButton)htControls[1];
                        currentButtonColor = currentfocus.PanelColor;


                    }
                }
            }
            else
            {
                MessageBox.Show("Testing is in progress");
            }
        }
        #endregion

        #region when blackhawk button is clicked
        private void customButton1_Click_1(object sender, EventArgs e)
        {
            Console.WriteLine(((CustomButton)sender).Name);
            ((CustomButton)sender).Focus();
            //   currentfocus.BorderStyle = BorderStyle.None;
            //  ((CustomButton)sender).BorderStyle = BorderStyle.FixedSingle;
            currentfocus.PanelColor = currentButtonColor;

            currentButtonColor = ((CustomButton)sender).PanelColor;
            currentfocus = (CustomButton)sender;



        }
        #endregion

        #region import excel or csv file
        private void Excel2CSV_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter =
               "All files (*.*)|*.*|XLS files (*.xls)|*.xls|CSV files (*.csv)|*.csv";
            dialog.InitialDirectory = ".";
            dialog.Title = "Select the file to import";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                Console.WriteLine(dialog.FileName);
                strFilePath = dialog.FileName;
                string ext = Path.GetExtension(strFilePath);
                if (ext.ToUpper() == ".XLS")
                {
                    try
                    {
                        File.Delete("fill.csv");
                        Form csvData = new FormCSVData(strFilePath);
                        //csvData.ShowDialog();
                        csvData.Dispose();

                        if (Globals.csvCreated)
                        {
                            progress = new frmImportingProgress("fill.csv");

                          //  progress.Visible = false;
                           // progress.ShowDialog();
                            Globals.csvCreated = false;
                        }
                        else
                        {
                            MessageBox.Show("Unable to read the Excel File, Try this:\nSave this file as csv file using excel\nthen save it back to xls file (use a new name)\nand import the new xls file instead.", "Read Excel failed");
                        }
                    }
                    catch (IOException ee)
                    {
                        MessageBox.Show(ee.Message, "Error");
                        // file is in use.

                    }
                }
                else if (ext.ToUpper() == ".CSV")
                {
                    progress = new frmImportingProgress(strFilePath);

  //                  progress.Visible = false;
   //                 progress.ShowDialog();
                }
                else
                {
                    MessageBox.Show(ext + " file format is not supported.", "Unsupported format");
                }
 //               unitButton1.Focus();
//                currentfocus = unitButton1;
      //          progress.Focus();

            }


        }
        #endregion

        #region double click blackhawk button to show the details and errors.
        private void customButton1_DoubleClick(object sender, EventArgs e)
        {
            int htIndex = Int16.Parse(((CustomButton)sender).Name.Substring(10));
            Console.WriteLine("Double Clicked");
            FormBHDetail BHDetail = new FormBHDetail(htBlackhawks[htIndex].ToString(), htErorr[htIndex].ToString(), htValid[htIndex].ToString());

            BHDetail.Show();


        }
        #endregion

        private void MoveToBlackhawkSet()
        {
            string passedID = "";
            foreach (int key in htBlackhawks.Keys)
            {

                if (htPassed[key].ToString() == "1")
                {

                    passedID = passedID + htBlackhawks[key].ToString() + ",";

                }
            }
            int deviceSetID = Globals.DeviceSetService.GetDeviceSetID("Blackhawk");
            string[] arrPassedID = passedID.Split(',');
            Globals.DeviceSetService.AddDevicesToDeviceSet(arrPassedID, deviceSetID);
        }

        private void btnOptions_Click(object sender, EventArgs e)
        {
            if (testing)
            {
                MessageBox.Show("Testing is in progress");
            }
            else
            {

                FormOptions frmOptions = new FormOptions();
                frmOptions.ShowDialog();
                if (Globals.resetPassed)
                {
                    for (int i = 1; i <= htControls.Count; i++)
                    {

                        if (htPassed[i].ToString() == "1")
                        {
                            htPassed[i] = 0;
                        }
                    }

                    Globals.resetPassed = false;
                }
            }
        }



        private void Layers_SizeChanged(object sender, EventArgs e)
        {
            SetButtonLocation(((Panel)sender).Width, ((Panel)sender).Height);

        }

        private void KeyPassed_Click(object sender, EventArgs e)
        {
            MessageBox.Show("lalala");

        }

        private void btnDone_Click(object sender, EventArgs e)
        {
            if (testing)
            {
                MessageBox.Show("Testing is in progress");
            }
            else
            {
                if (MessageBox.Show("Move Passed units to Blackhawk device set?", "Confirm moving", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    MoveToBlackhawkSet();
                    for (int i = 1; i <= htBlackhawks.Count; i++)
                    {
                        if (htPassed[i].ToString() == "1")
                        {
                            htPassed[i] = 0;
                            ((CustomButton)htControls[i]).PanelColor = Color.White;
                            htValid[i] = 0;
                            if (currentfocus == ((CustomButton)htControls[i]))
                            {
                                currentButtonColor = Color.White;
                            }
                            htBlackhawks[i] = "None";
                            ((CustomButton)htControls[i]).Caption = "Moved";

                        }
                    }
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {


            if (testing)
            {
                MessageBox.Show("Testing is in progress");
            }
            else
            {

                if (MessageBox.Show("Clear all blackhawks?", "Are you sure?", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {


                    for (int i = 1; i <= htBlackhawks.Count; i++)
                    {
                        htErorr[i] = "Errors(if any):";
                        htPassed[i] = 0;
                        ((CustomButton)htControls[i]).PanelColor = Color.White;
                        htValid[i] = 0;
                        if (currentfocus == ((CustomButton)htControls[i]))
                        {
                            currentButtonColor = Color.White;
                        }
                        htBlackhawks[i] = "None";
                        ((CustomButton)htControls[i]).Caption = "";

                    }
                    unitButton1.Focus();
                    currentfocus = unitButton1;
                    currentButtonColor = currentfocus.PanelColor;

                }
            }
        }






    }
}

