

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Jdas_Mbic
{
    public partial class JdasMbic : Form
    {
        const double Table_Dbm_DefaultValue = 0;//31.5;
        const int Table_DL_DefaultValue = 5;
        const int Table_UL_DefaultValue = -15;
        const int Table_Temp_DefaultValue = -10;
        Serial serial = new Serial(); // Uart Open
        enum DLUL_Category
        {
            DL_DET = 0,
            UL_DET
        };


        public JdasMbic()
        {
            InitializeComponent();
        }

        private void JdasMbic_Load(object sender, EventArgs e)
        {
            ATT_TableLayoutSetting();
            serial.Serial_Initialize(ref comboBox_Port);

        }
        
        private void ATT_TableLayoutSetting()
        {
            double TempDbmData = Table_Dbm_DefaultValue;
            string tempstr = "";
            for (int i = 0; i < 64; i++)
            {
                dataGridView_TableSetting.Rows.Add();
                tempstr = string.Format("{0:0.0}", TempDbmData);
                dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " dBm"; ;
                TempDbmData = TempDbmData + 0.5;
                
            }

            foreach (DataGridViewRow row in this.dataGridView_TableSetting.Rows)
            {
                row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
            }
            this.dataGridView_TableSetting.AutoResizeRowHeadersWidth(
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            this.dataGridView_TableSetting.TopLeftHeaderCell.Value = "No.";
            dataGridView_TableSetting.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView_TableSetting.ClearSelection();
        }


        private void DET_TableLayoutSetting(DLUL_Category cat)
        {
            string tempstr = "";
            DLUL_Category tempenum = cat;

            switch (tempenum) {
                case DLUL_Category.DL_DET:
                    double Temp_DL_Data = Table_DL_DefaultValue;
                    for (int i = 0; i < 31; i++)
                    {
                        dataGridView_TableSetting.Rows.Add();
                        tempstr = string.Format("{0:0}", Temp_DL_Data);
                        dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " dBm";
                        Temp_DL_Data = Temp_DL_Data - 1;

                    }
                    break;
                case DLUL_Category.UL_DET:
                    double Temp_UL_Data = Table_UL_DefaultValue;
                    for (int i = 0; i < 46; i++)
                    {
                        dataGridView_TableSetting.Rows.Add();
                        tempstr = string.Format("{0:0}", Temp_UL_Data);
                        dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " dBm";
                        Temp_UL_Data = Temp_UL_Data - 1;
                    }
                    break;
            }
            foreach (DataGridViewRow row in this.dataGridView_TableSetting.Rows)
            {
                row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
            }
            this.dataGridView_TableSetting.AutoResizeRowHeadersWidth(
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            this.dataGridView_TableSetting.TopLeftHeaderCell.Value = "No.";
            dataGridView_TableSetting.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView_TableSetting.ClearSelection();

        }
        private void Temp_TableLayoutSetting()
        {
            string tempstr = "";
            
            double Temp_Data = Table_Temp_DefaultValue;
            for (int i = 0; i < 10; i++)
            {
                dataGridView_TableSetting.Rows.Add();
                tempstr = string.Format("{0:0}", Temp_Data);
                dataGridView_TableSetting[0, i].Value = Convert.ToString(tempstr) + " ℃";
                Temp_Data = Temp_Data - 5;

            }
            foreach (DataGridViewRow row in this.dataGridView_TableSetting.Rows)
            {
                row.HeaderCell.Value = String.Format("{0}", row.Index + 1);
            }
            this.dataGridView_TableSetting.AutoResizeRowHeadersWidth(
            DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);
            this.dataGridView_TableSetting.TopLeftHeaderCell.Value = "No.";
            dataGridView_TableSetting.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridView_TableSetting.ClearSelection();
        }

        private void dataGridView_TableSetting_CellClick(object sender, DataGridViewCellEventArgs e)
        {

        }
        /*
         * 
         * TABLE Setting Area
         * 
         */
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ComboBox comboBox = (ComboBox)sender;
            string tempstr = comboBox.Text;

            switch (tempstr)
            {
                case "ATT_DL1":
                case "ATT_UL1": 
                case "ATT_DL2": 
                case "ATT_UL2": 
                case "ATT_DL3": 
                case "ATT_UL3": 
                case "ATT_DL4": 
                case "ATT_UL4": 
                    dataGridView_TableSetting.Rows.Clear();
                    ATT_TableLayoutSetting();
                    break;
                case "DET_DL1": 
                case "DET_DL2": 
                case "DET_DL3": 
                case "DET_DL4":
                    dataGridView_TableSetting.Rows.Clear();
                    DET_TableLayoutSetting(DLUL_Category.DL_DET);
                    break;
                case "DET_UL1": 
                case "DET_UL2": 
                case "DET_UL3": 
                case "DET_UL4":
                    dataGridView_TableSetting.Rows.Clear();
                    DET_TableLayoutSetting(DLUL_Category.UL_DET);
                    break;
                case "TEMP_DL1": 
                case "TEMP_UL1": 
                case "TEMP_DL2": 
                case "TEMP_UL2": 
                case "TEMP_DL3": 
                case "TEMP_UL3": 
                case "TEMP_DL4": 
                case "TEMP_UL4": 
                    dataGridView_TableSetting.Rows.Clear();
                    Temp_TableLayoutSetting();
                    break;
                default:
                    MessageBox.Show("존재하지 않는 ComboBox 입니다.\r\n 확인해주세요.");
                    break;
            }
           
                
        }
        private List<int> DataGridViewIndexOutput()
        {
            List<int> Tmplist = new List<int>();

            Int32 selectedCellCount =
            dataGridView_TableSetting.GetCellCount(DataGridViewElementStates.Selected);
            if (selectedCellCount > 0)
            {
                    System.Text.StringBuilder sb =
                        new System.Text.StringBuilder();

                    //for (int i = 0;i < selectedCellCount; i++)
                    for (int i = 0; i < selectedCellCount; i += 2)
                    {
                        sb.Append("Row: ");
                        sb.Append(dataGridView_TableSetting.SelectedCells[i].RowIndex.ToString());
                        Tmplist.Add(dataGridView_TableSetting.SelectedCells[i].RowIndex);
                        /*sb.Append(", Column: ");
                        sb.Append(dataGridView_TableSetting.SelectedCells[i].ColumnIndex.ToString());*/
                        sb.Append(Environment.NewLine);
                    }

                    // sb.Append("Total: " + selectedCellCount.ToString());
                   // MessageBox.Show(sb.ToString(), "Selected Cells");
            }
            return Tmplist;
        }
        private void button_MultiSet_Click(object sender, EventArgs e)
        {
            List<int> TmpList = new List<int>();
            TmpList = DataGridViewIndexOutput();
            for(int i = 0; i < TmpList.Count; i++)
            {
                dataGridView_TableSetting[1, TmpList[i]].Value = numericUpDown_MultiSet.Value.ToString();
            }
        }

        private void button_Expansion_Click(object sender, EventArgs e)
        {
            List<int> TmpList = new List<int>();
            int Count = 0;
            double MaxVal = 0, MinVal = 0,Result = 0;
            double Tmpdata = 0;

            TmpList = DataGridViewIndexOutput();
            TmpList.Sort();

            Count = (TmpList[TmpList.Count - 1] - TmpList[0]);
            MaxVal = Convert.ToDouble(dataGridView_TableSetting[1,TmpList[TmpList.Count - 1]].Value);
            MinVal = Convert.ToDouble(dataGridView_TableSetting[1, TmpList[0]].Value);

            Result = (MaxVal - MinVal) / Count;

            for (int i = 0; i < (Count  - 1); i++)
            {
                Tmpdata = Convert.ToDouble(dataGridView_TableSetting[1, TmpList[0] + i].Value);
                dataGridView_TableSetting[1, TmpList[0] + (i + 1) ].Value = string.Format("{0:0.0}",Math.Round(Tmpdata + Result, 1));
            }

           /* for (int i = 0; i < TmpList.Count; i++)
            {
                dataGridView_TableSetting[1, TmpList[i]].Value = numericUpDown_MultiSet.Value.ToString();
            }*/
        }

        private void button_Initalize_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView_TableSetting.RowCount; i++)
            {
                dataGridView_TableSetting[1, i].Value = 0;
            }

        }

        private void button_CurrentOutput_Click(object sender, EventArgs e)
        {

        }

        private void button_MultiOffset_Click(object sender, EventArgs e)
        {
            List<int> TmpList = new List<int>();
            TmpList = DataGridViewIndexOutput();
            double CurrentVal = 0, SumVal = 0;

            for (int i = 0; i < TmpList.Count; i++)
            {
                CurrentVal = Convert.ToDouble(dataGridView_TableSetting[1, TmpList[i]].Value);
                SumVal = Convert.ToDouble(numericUpDown_MultiOffset.Value);
                dataGridView_TableSetting[1, TmpList[i]].Value = Convert.ToString(CurrentVal + SumVal);
            }
        }
     //   Bluecell_Serial bluecellserial = new Bluecell_Serial();

        private void button_PortOpen_Click(object sender, EventArgs e)
        {
            bool ret = false;
            ret = Serial_connectiondisable(serial.Serial_PortOpen(ref button_PortOpen, ref comboBox_Port));
            if (ret == false && timer_JdasMbic.Enabled == false)
            {
                timer_JdasMbic.Start(); //타이머를 발동시킨다.
            }
            else if (timer_JdasMbic.Enabled == true)
            {
                timer_JdasMbic.Stop(); //타이머를 멈춘다.
            }
            else
            {
                /*NOP*/
            }
            serial.Serial_Main_Form_Get(this);
        }

        private void button_terminal_Click(object sender, EventArgs e)
        {
            serial.Serial_TerminalOpen(serial);
        }
        
       
        public bool Serial_connectiondisable(Boolean on_off)
        {
            comboBox_Port.Enabled = on_off;
            comboBox_baudrate.Enabled = on_off;
            return on_off;
        }
        public bool TX_RX_Light = false;
        private delegate void StringSend(string Text);
        private delegate void GridviewSend(ref object gridview, string Text);
        private delegate void ByteSend(byte[] Text);

        int offset = 0;
        byte[] rxBuffer;
#if false
        private void sPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string startStr = "V";
            string endStr = "\n";

            try
            {

                if (offset == 0)
                {
                    rxBuffer = new byte[4096];
                }

                string rxString = "";
                int intRecSize = serialPort_JdasMbic.BytesToRead;

                if (intRecSize != 0)
                {




                    /* if (panel_GpsTest.Visible == true)
                     {
                         byte[] btdata = new byte[intRecSize];
                         serialPort_JdasMbic.Read(btdata, 0, intRecSize);
                         string data = Encoding.Default.GetString(rxBuffer);

                         this.Invoke(new StringSend(Data_Recv_Str), data);
                     }
                     else*/
                    {
                        serialPort_JdasMbic.Read(rxBuffer, offset, intRecSize);
                        offset += intRecSize;
                        for (int iTemp = 0; iTemp < offset; iTemp++)
                        {
                            rxString += Convert.ToChar(rxBuffer[iTemp]);
                        }
                        /*
                         * 
                         * Example
                         * if (panel_SensorTest.Visible == true)
                        {
                            startStr = "V";
                            endStr = "\n";
                        }

                        else if (panel_Catm1Test.Visible == true)
                        {
                            startStr = "B";
                            endStr = "\n";
                        }
                        else if (panel_GpsTest.Visible == true)
                        {
                            startStr = "$";
                            endStr = "\n";
                        }
                        
                         */
                        if (rxString.Contains(startStr))
                        {
                            rxString = rxString.Substring(rxString.IndexOf(startStr));
                            if (rxString.Contains(endStr))
                            {
                                this.Invoke(new StringSend(Data_Recv_Str), rxString);
                                //program.dataReceived(rxString, "Receive");
                                offset = 0;
                            }
                        }
                        else
                        {
                            this.Invoke(new StringSend(Data_Recv_Str), rxString);
                            offset = 0;
                        }
                    }

                }
            }
            catch { }

        }
#endif

        int LineLimit = 500;
        [DllImport("user32.dll")]
        public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
        private const int WM_SETREDRAW = 11;
        public void Data_Recv_Str(string text)
        {

            System.Windows.Forms.RichTextBox tbReceived = null;
            //tbReceived = richTextBox_Sensor;

            int nLimitLines = Convert.ToInt32(LineLimit); //제한 라인 수
            try
            {
                try
                {
                    SendMessage(this.Handle, WM_SETREDRAW, false, 0);
                }
                catch (Exception e) { MessageBox.Show(e.StackTrace); }
                if (tbReceived.Lines.Length > nLimitLines)
                {
                    LinkedList<string> tempLines = new LinkedList<string>(tbReceived.Lines);
                    while ((tempLines.Count - nLimitLines) > 0)
                    {
                        tempLines.RemoveFirst();
                    }
                    tbReceived.Lines = tempLines.ToArray();
                }
                try
                {
                    SendMessage(this.Handle, WM_SETREDRAW, true, 0);
                }
                catch { return; }
                /* Example
                if (panel_SensorTest.Visible == true)
                {

                    Sensor_TestFunc(text);
                    tbReceived.AppendText(text);
                }
                else
                {
                    tbReceived.AppendText(text);
                }

                */
                
              tbReceived.SelectionStart = tbReceived.Text.Length;//맨 마지막 선택... 
                tbReceived.ScrollToCaret();
            }
            catch { try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } }
        }
        public void Data_Recv_Str(byte[] text)
        {
            string strtext = Encoding.Default.GetString(text);

            System.Windows.Forms.RichTextBox tbReceived = null;
          
//            tbReceived = richTextBox_Sensor;

            int nLimitLines = Convert.ToInt32(LineLimit); //제한 라인 수
            try
            {
                try
                {
                    SendMessage(this.Handle, WM_SETREDRAW, false, 0);
                }
                catch (Exception e) { MessageBox.Show(e.StackTrace); }
                if (tbReceived.Lines.Length > nLimitLines)
                {
                    LinkedList<string> tempLines = new LinkedList<string>(tbReceived.Lines);
                    while ((tempLines.Count - nLimitLines) > 0)
                    {
                        tempLines.RemoveFirst();
                    }
                    tbReceived.Lines = tempLines.ToArray();
                }
                try
                {
                    SendMessage(this.Handle, WM_SETREDRAW, true, 0);
                }
                catch { return; }
                /* Example
                if (panel_SensorTest.Visible == true)
                {
                    Sensor_TestFunc(strtext);
                    tbReceived.AppendText(strtext);
                }
                else
                {
                    tbReceived.AppendText(strtext);
                }
                */
                tbReceived.SelectionStart = tbReceived.Text.Length;//맨 마지막 선택... 
                tbReceived.ScrollToCaret();
            }
            catch { try { SendMessage(this.Handle, WM_SETREDRAW, true, 0); } catch { return; } }
        }
        Int64 Timer_Cnt = 0;
        Int32 ReqTimer_Cnt = 0;

        private void timer1_Tick(object sender, EventArgs e)
        {
            Update_Serial update_Serial = null;
            bool req_set = false;
            if (update_Serial == null)
            {
                update_Serial = (Update_Serial)serial.FileDownloadClass_Get();
                if (update_Serial == null)
                    req_set = true;
                else if (update_Serial.Update_ready == false)
                    req_set = true;
            }
            if (req_set)
            {
                ReqTimer_Cnt++;
            }
            if (TX_RX_Light == true)
            {
                Timer_Cnt++;
            }
            if (Timer_Cnt < 1000)
            {
                if (this.pictureBox_G_TX.Visible == true)
                {
                    TX_Light_OFF();
                }
                if (this.pictureBox_G_RX.Visible == true)
                {
                    RX_Light_OFF();
                }
                Timer_Cnt = 0;
                TX_RX_Light = false;
            }
            if (ReqTimer_Cnt > 6)
            {
                // bluecell_BootProtocol.Bluecell_RF_Status_Req(serial);
                ReqTimer_Cnt = 0;
            }
        }

        private void radioButton_ATT_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton radioButton = (RadioButton)sender;

            switch (radioButton.Text)
            {
                case "ATT1":
                    label_Table_ATTDL.Text = "ATT_DL1";
                    label_Table_ATTUL.Text = "ATT_UL1";
                    break;
                case "ATT2":
                    label_Table_ATTDL.Text = "ATT_DL2";
                    label_Table_ATTUL.Text = "ATT_UL2";
                    break;
                case "ATT3":
                    label_Table_ATTDL.Text = "ATT_DL3";
                    label_Table_ATTUL.Text = "ATT_UL3";
                    break;
                case "ATT4":
                    label_Table_ATTDL.Text = "ATT_DL4";
                    label_Table_ATTUL.Text = "ATT_UL4";
                    break;
               
                    
                
            }
        }

        private void button_TableDL_Click(object sender, EventArgs e)
        {

        }

        private void button_TableUL_Click(object sender, EventArgs e)
        {

        }
        Update_Serial file = new Update_Serial();
        private void button_FirmwareUpdate_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            //FileDownload file = new FileDownload();
            if (setcheck_checkBox.Checked == true)
                setcheck_checkBox.Checked = false;
            file.ShowFileOpenDialog(ref serial, ofd);
        }
        public void TX_Light_ON()
        {
            this.pictureBox_G_TX.Visible = true;
            this.pictureBox_R_TX.Visible = false;
        }
        public void TX_Light_OFF()
        {
            this.pictureBox_R_TX.Visible = true;
            this.pictureBox_G_TX.Visible = false;
        }
        public void RX_Light_ON()
        {
            this.pictureBox_G_RX.Visible = true;
            this.pictureBox_R_RX.Visible = false;
        }
        public void RX_Light_OFF()
        {
            this.pictureBox_R_RX.Visible = true;
            this.pictureBox_G_RX.Visible = false;
        }
        const byte BLUECELL_RESET_LENGTH = 7;
        public const byte BLUECELL_HEADER = 0xBE;
        public const byte BLUECELL_TAILER = 0xEB;

        private void button_DL1_Click(object sender, EventArgs e)
        {
     
            byte[] temp_buf = new byte[BLUECELL_RESET_LENGTH];

            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Header]   = BLUECELL_HEADER;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Type]     = 0x01;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_Length]   = 6;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_CrcIndex] = 5;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data]     = 1;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 1] = 1;
            temp_buf[(int)Bluecell_ProtIndex_p.Bluecell_data + 2] = 1;
            serial.Serial_DataSend(temp_buf, temp_buf.Length);
        }

        private void button_UL1_Click(object sender, EventArgs e)
        {

        }

        private void button_DL3_Click(object sender, EventArgs e)
        {

        }

        private void button_UL3_Click(object sender, EventArgs e)
        {

        }

        private void button_DL4_Click(object sender, EventArgs e)
        {

        }

        private void button_UL4_Click(object sender, EventArgs e)
        {

        }

        private void button_DL2_Click(object sender, EventArgs e)
        {

        }

        private void button_UL2_Click(object sender, EventArgs e)
        {

        }
    }
}
