using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;

using System.Threading;
using System.IO.Ports;

using LFP_Manager.DataStructure;
using LFP_Manager.Function;
using LFP_Manager.Utils;

namespace LFP_Manager.Controls
{
    public delegate void DataUpdate(object sender, DeviceSystemData[] aSystemData);

    public partial class ucSerialProcess : DevExpress.XtraEditors.XtraUserControl
    {
        #region VARIABLES

        DeviceSystemData[] SystemData;

        //Thread serialComm = null;
        SerialPort sPort = null;
        //string CommPort = null;

        bool SerialPortThreadEnd = false;

        public event DataUpdate OnUpdate = null;

        #endregion

        #region CONSTRUCTORS

        public ucSerialProcess(DeviceSystemData[] aSystemData)
        {
            InitializeComponent();

            SystemData = aSystemData;
        }

        #endregion

        #region COMMPORT CONTROLS

        private bool Open(string cPort, int cBaudrate)
        {
            bool result = false;

            sPort = new SerialPort();
            sPort.PortName = cPort;
            sPort.BaudRate = cBaudrate;

            try
            {
                sPort.Open();

                result = true;
            }
            catch (Exception)
            {
            }

            return result;
        }

        private void Close()
        {
            if (sPort != null)
            {
                if (sPort.IsOpen)
                {
                    sPort.Close();
                }
                sPort = null;
            }
        }

        #endregion

        #region Serial Comm Thread

        ushort RequestRegAddr = 0x0000;
        ushort RequestRegLen = 50;
        int SS, bakSS;

        private int SerialTxProcess()
        {
            byte[] sData;

            SS = DateTime.Now.Second;

            if ((SS == 58) && (bakSS != SS))
            {
                // Write
                RequestRegAddr = 19;
                RequestRegLen = 5;
                sData = csSerialCommFunction.MakeWriteRegisterData(0xFF, RequestRegAddr, RequestRegLen);
                sPort.Write(sData, 0, sData.Length);
                bakSS = SS;

                return 0;
            }
            else
            {
                // Read
                RequestRegAddr = 0x0000;
                RequestRegLen = 50;
                sData = csSerialCommFunction.MakeReadRegisterData(0x01, RequestRegAddr, RequestRegLen);
                sPort.Write(sData, 0, sData.Length);
                bakSS = SS;

                return 1;
            }
        }

        #region Serial Buffering

        private void PutBuff(byte c)
        {
            rBuffer[rBufStart++] = c;
            rBufStart %= BUFFER_SIZE;

            if (rBufStart == rBufEnd)
            {
                rBufEnd++;
                rBufEnd %= BUFFER_SIZE;
            }
        }

        private int GetBuff()
        {
            int result = 0;

            if (rBufStart != rBufEnd)
            {
                result = 0x0100 + rBuffer[rBufEnd++];
                rBufEnd %= BUFFER_SIZE;
            }
            return result;
        }

        #endregion

        const int BUFFER_SIZE = 512;

        byte[] rBuffer = new byte[BUFFER_SIZE];
        int rBufStart = 0;
        int rBufEnd = 0;

        byte[] ReadBuf = new byte[BUFFER_SIZE];
        ushort rPosition = 0;
        bool Commfail = true;
        bool disCommfail = false;

        ushort BTCU_ID = 1;

        private void serialRecvThread()
        {
            int getData = 0;
            byte cData = 0;
            bool BuffStart = false;
            int TimeOutCount = 0;

            while (SerialPortThreadEnd == false)
            {
StartSend:
                if (sPort.IsOpen)
                {
                    if (SerialTxProcess() == 1)
                    {
                        int rTimeOut = 100;

                        BuffStart = false;
                        rPosition = 0;

                        while (rTimeOut > 0)
                        {
                            if (((getData = GetBuff()) & 0x0100) != 0x0000)
                            {
                                rTimeOut = 100;
                                TimeOutCount = 0;

                                cData = (byte)(getData & 0x00FF);

                                if (rPosition >= BUFFER_SIZE)
                                {
                                    BuffStart = false;
                                    rPosition = 0;
                                }

                                if (BuffStart == false)
                                {
                                    rPosition = 0;
                                    if (cData == 0x01)
                                    {
                                        ReadBuf[rPosition++] = cData;
                                        BuffStart = true;
                                    }
                                }
                                else
                                {
                                    ReadBuf[rPosition++] = cData;

                                    switch (csSerialCommFunction.ModbusPacketFromSlaveCheck(ReadBuf, rPosition))
                                    {
                                        case 0:         // Need more data
                                            break;
                                        case 1:         // Packet OK, no error
                                            byte[] cdata = csUtils.StrToByteArray(ReadBuf, 0, rPosition - 2);

                                            Commfail = false;
                                            SystemData[0] = csSerialCommFunction.SerialRxProcess(ReadBuf, RequestRegAddr, rPosition, SystemData[0]);

                                            if (OnUpdate != null)
                                            {
                                                OnUpdate(this, SystemData);
                                            }

                                            Thread.Sleep(100);

                                            goto StartSend;
                                        case -1:        // Packet error
                                            rPosition = 0;
                                            BuffStart = false;

                                            Thread.Sleep(100);

                                            goto StartSend;
                                        default:
                                            break;
                                    }
                                }
                            }
                            else
                            {
                                Thread.Sleep(1);
                                if (rTimeOut > 0) rTimeOut--;
                            }
                        }

                        if (rPosition > 0)
                        {
                            Thread.Sleep(100);
                        }
                        else
                        {
                            TimeOutCount++;
                            if (TimeOutCount >= 5)
                            {
                                TimeOutCount = 5;
                                Commfail = true;
                            }
                            //if (Commfail == true)
                            //{
                            //    BTCU_ID++;
                            //    BTCU_ID %= 31;
                            //    if (BTCU_ID == 0) BTCU_ID = 1;
                            //}
                            Thread.Sleep(100);
                        }
                    }
                    else
                    {
                        Thread.Sleep(100);
                    }
                    rPosition = 0;
                }
                else
                {
                    Thread.Sleep(500);
                }
            }
        }

        #endregion
    }
}
