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

namespace EQTrack
{
    public partial class frmImportingProgress : Form
    {
        public frmImportingProgress(string fileName)
        {
            InitializeComponent();
            this.Show();
            InsertCSV(fileName);
        }

        public void setText(string text)
        {

            txtboxProgress.AppendText(text + "\n");

        }
        #region upload blackhawks into blackhawk database through csv file
        private void InsertCSV(string fileName)

        {
            System.IO.StreamReader reader = null;
            string csv = "";
            bool readCSV = false;
            try
            {
                reader = new System.IO.StreamReader(fileName);
                csv = reader.ReadToEnd();
                reader.Close();
                readCSV = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "Cannot read CSV file");
                setText("The importing file is being used by other program (probably excel), please close that program and try again.");
            }

            if (readCSV)
            {
                string[] csvArray = csv.Split('\n');
                int counter = 0;
                int total = csvArray.Length - 2;
                //  MessageBox.Show(csvArray[0]);
                string column_name = csvArray[0];
                for (int i = 1; i < csvArray.Length; i++)
                {
                    //  MessageBox.Show(column_name + "\n" + csvArray[i]);
                    if (csvArray[i] == "" || csvArray[i] == "\r")
                    {
                        break;
                    }
                    string csvParam = column_name + "\n" + csvArray[i];
                    csvArray[i] = csvArray[i].Replace("\r", "");
                    string[] values = csvArray[i].Split(',');
                    string SN = values[2];
                    DataTable dt = null;
                    try
                    {
                        dt = Globals.DeviceService.GetDeviceStatus(SN);
                    }
                    catch (Exception e)
                    {
                        MessageBox.Show(e.Message, "Error Get Device Status");
                    }

                    if (dt == null)
                    {
 //                       MessageBox.Show("Failed to get status from Blackhawk server.");
                        setText("Failed to get status from Blackhawk server.");
                        Application.DoEvents();
                    }
                    else if (dt.Rows.Count > 0)
                    {
//                        MessageBox.Show(SN + " is already in the Blackhawk database");
                        setText(SN + " is already in the Blackhawk database");
                        Application.DoEvents();
                        

                    }
                    else
                    {
                        //  MessageBox.Show(SN);

                        try
                        {

                            Globals.FactoryService.UploadDevicesFromCSV(csvParam, "Blackhawks4.csv", true);

                        }
                        catch (Exception ee)
                        {
                            if (ee.Message == "Server was unable to process request. ---> Collection was modified; enumeration operation might not execute.")
                            {
                            }
                            else
                            {
                                MessageBox.Show(ee.Message, "Error importing");
                            }
                        }
                        try
                        {
                            Globals.DeviceService.SetEnable(SN, true);
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.Message, "Error set enable");
                        }

                        if (validImport(SN, values))
                        {

                            setText("Blackhawk " + SN + " is imported successfully");
                            Application.DoEvents();
                            counter++;
                        }
                        else
                        {
                            setText("failed to import blackhawk " + SN );
                            Application.DoEvents();
                        }
                    }
                }
                setText(counter + " of " + total + " Blackhawks have been imported successfully");
             //   Application.DoEvents();

            }
        }
        #endregion
        #region check if import succesfully
        private bool validImport(string SN, string[] values)
        {



            DataTable dt = null;
            try
            {

                dt = Globals.DeviceService.GetDeviceStatus(SN);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "erorr get device status");
            }

            if (dt == null || dt.Rows.Count == 0)
            {
                setText("Cannot find Blackhawk " + SN + " on server");
                return false;
            }
            else
            {


                string importError = "";
                bool result = true;
                string debug = "";
                debug = dt.Rows[0]["Phone_Number"].ToString();
                if (dt.Rows[0]["Phone_Number"].ToString() != values[1])
                {
                    importError += "\nPhone_Number doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Enabled"].ToString().ToUpper() != num2str(values[5]))
                {
                    importError += "\nEnabled doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["BHN"].ToString() != values[8])
                {
                    importError += "\nSerial_Number doesn't match";
                    result = false;
                }
                debug = dt.Rows[0]["IMS"].ToString();
                if (dt.Rows[0]["IMS"].ToString() != values[0])
                {
                    importError += "\nIMS doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["TRI_Days"].ToString() != values[9])
                {
                    importError += "\nTRI_Days doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["TRI_Hours"].ToString() != values[10])
                {
                    importError += "\nTRI_Hours doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["TRI_Minutes"].ToString() != values[11])
                {
                    importError += "\nTRI_Minutes doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["TRI_Seconds"].ToString() != values[12])
                {
                    importError += "\nTRI_Seconds doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["OSI"].ToString() != values[13])
                {
                    importError += "\nOSI doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Panic_Alert"].ToString().ToUpper() != num2str(values[14]))
                {
                    importError += "\nPanic_Alert doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Alarm_Alert"].ToString().ToUpper() != num2str(values[15]))
                {
                    importError += "\nAlarm_Alert doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Lock_Door_Control"].ToString().ToUpper() != num2str(values[16]))
                {
                    importError += "\nLock_Door_Control doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Unlock_Door_Control"].ToString().ToUpper() != num2str(values[17]))
                {
                    importError += "\nUnlock_Door_Control doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Low_Battery_Indicator"].ToString().ToUpper() != num2str(values[18]))
                {
                    importError += "\nLow_Battery_Indicator doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Disconnected_Battery_Indicator"].ToString().ToUpper() != num2str(values[19]))
                {
                    importError += "\nDisconnected_Battery_Indicator doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Crash_Sensor"].ToString().ToUpper() != num2str(values[20]))
                {
                    importError += "\nCrash_Sensor doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Low_Power_Mode"].ToString().ToUpper() != num2str(values[21]))
                {
                    importError += "\nLow_Power_Mode doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Over_Speed_Indicator"].ToString().ToUpper() != num2str(values[22]))
                {
                    importError += "\nOver_Speed_Indicator doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Immobilizer"].ToString().ToUpper() != num2str(values[23]))
                {
                    importError += "\nImmobilizer doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Ignition_Monitoring"].ToString().ToUpper() != num2str(values[24]))
                {
                    importError += "\nIgnition_Monitoring doesn't match";
                    result = false;
                }
                debug = dt.Rows[0]["HeartbeatRate"].ToString();
                if (dt.Rows[0]["HeartbeatRate"].ToString().ToUpper() != (values[26]))
                {
                    importError += "\nHeartbeatRate doesn't match";
                    result = false;
                }
                if (dt.Rows[0]["Key"].ToString() != (values[3]))
                {
                    importError += "\nKey doesn't match";
                    result = false;
                }
                if (importError != "")
                {
                    MessageBox.Show("Following error occur, please contact Blackhawk: \n" + importError);
                    setText("Blackhawk " + SN + " is imported to the server, but some data is modified");
                }
                return result;
            }
        }
        #endregion
        private string num2str(string num)
        {
            if (num == "1")
            {
                return "TRUE";
            }
            else if (num == "0")
            {
                return "FALSE";
            }
            else
            {
                return "NOTHING";
            }

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }


    }
}