using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Text.RegularExpressions;
using System.Collections;
using GcDevicePc.Common;
using GcDevicePc.GCBuffer;
using System.Runtime.InteropServices;
using CKVocAnalyzer;

namespace GcDevicePc.ProThread
{
    class ChannelDataSave2
    {
        ManualResetEvent datamre = new ManualResetEvent(false);
        Thread t_DataSave;
        String savefilename;

        private long GetCurrentTimeUnix()
        {
            TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)));
            long t = (long)cha.TotalSeconds;
            return t;
        }

        #region
        private void Monitor_Data()
        {
            double value = 0;
            float dvalue = 0.0f;
            UInt32 starttimer = 0x7FFFFFFF;
            UInt32 endtimer = 0x7FFFFFFF;
            Boolean saveflag = false;
            List<float> listPoint = new List<float>();//临时数据区
            List<float> savePoint = new List<float>();
            List<uint> timePoint = new List<uint>();//临时数据区

            try
            {
                while (!datamre.WaitOne(500))
                {
                    if ((globaldata.m_hmibuffer.gcinfo.methodstatus == 4 || globaldata.m_hmibuffer.gcinfo.methodstatus == 5) || globaldata.m_pcbuffer.gcpcinfo.pcworkinfo.system_Statue)
                    {
                        String tmpFileName = globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_MethodName;
                        String methodfilename = tmpFileName.Substring(tmpFileName.LastIndexOf("\\") + 1);
                        string[] sArray = methodfilename.Split('.');

                        String tmpfolder = Path.Combine(globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder, sArray[0]);
                        if (!Directory.Exists(tmpfolder))
                        {
                            Directory.CreateDirectory(tmpfolder);
                        }

                        tmpfolder = Path.Combine(tmpfolder, DateTime.Now.ToString("yyyyMMdd"));
                        if (!Directory.Exists(tmpfolder))
                        {
                            Directory.CreateDirectory(tmpfolder);
                        }

                        String cur_folder = tmpfolder;
                        String cur_filename = sArray[0] + "_" + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒") + "_中.hw";

                        savefilename = Path.Combine(cur_folder, cur_filename);

                        //  savefilename = globaldata.m_pcbuffer.gcpcinfo.pcfolderinfo.DataFolder + "\\" + DateTime.Now.ToString("yyyyMMdd") + "\\" + sArray[0] + "_" + DateTime.Now.ToString("yyyy年MM月dd日HH时mm分ss秒") + "_中.hw";

                        lock (globaldata.m_signalbuffer.Save_Port2)
                        {
                            if (globaldata.m_signalbuffer.Save_Port2.Count > 1)
                            {
                                if (globaldata.m_hmibuffer.gcinfo.methodstatus < 3 || globaldata.m_hmibuffer.gcinfo.methodstatus > 5)
                                {
                                    starttimer = ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Save_Port2[0]).ctimer;
                                    globaldata.m_signalbuffer.Save_Port2.Clear();
                                    if (saveflag)
                                    //if (globaldata.m_hmibuffer.gcinfo.methodstatus > 5 && saveflag)
                                    {
                                        starttimer = globaldata.m_hmibuffer.gcinfo.NowStartTime;
                                        endtimer = globaldata.m_hmibuffer.gcinfo.NowEndTime;

                                        //Log.Info("Channel2 Save Data: " + starttimer.ToString() + "-" + endtimer.ToString());
                                        //int index1 = timePoint.IndexOf(starttimer);

                                        int index1 = timePoint.FindIndex(item => item >= starttimer);
                                        // int index2 = timePoint.FindIndex(item => item >= endtimer);
                                        // int index2 = timePoint.FindIndex(item => item >= endtimer);
                                        int index2 = timePoint.FindLastIndex(item => item <= endtimer);

                                        if (index1 >= 0)
                                        {
                                            if (index2 <= 0)
                                            {
                                                index2 = timePoint.Count;
                                            }
                                        }

                                        if (index2 > index1 && index1 >= 0)
                                        {
                                            savePoint = listPoint.GetRange(index1, index2 - index1);

                                            TWFile twfile = new TWFile(savefilename);
                                            twfile.TW_Open();
                                            for (int j = 0; j < savePoint.Count; j++)
                                            {
                                                twfile.bw.Write((int)(savePoint[j] * 1000));
                                            }
                                            twfile.TW_Close(savePoint.Count);
                                        }
                                        else
                                        {
                                            Log.Info("Channel2 Save Data: " + starttimer.ToString() + "-" + endtimer.ToString());
                                            Log.Info("Channel2 Index1,Index2: " + index1.ToString() + "-" + index2.ToString());
                                            Log.Info("Channel2 timePoint: " + timePoint[0].ToString() + "-" + timePoint[timePoint.Count - 1].ToString());
                                            Log.Info("Channel2 Data Num:" + listPoint.Count.ToString());

                                            //Log.Info("Channel2 Data Num:" + listPoint.Count.ToString());
                                        }

                                        starttimer = 0x7FFFFFFF;
                                        savePoint.Clear();
                                        saveflag = false;
                                    }
                                }
                                else if (globaldata.m_hmibuffer.gcinfo.methodstatus == 4 || globaldata.m_hmibuffer.gcinfo.methodstatus == 5)
                                {
                                    for (int i = 0; i < globaldata.m_signalbuffer.Save_Port2.Count; i++)
                                    {
                                        if (globaldata.m_hmibuffer.gcinfo.NowStartTime <= ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Save_Port2[i]).ctimer)//&& (((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Save_Port[i]).ctimer - starttimer) < 3000)
                                        {
                                            value = (((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Save_Port2[i]).cdata * 1000.0f);
                                            dvalue = (float)Math.Round(value, 4);

                                            lock (timePoint)
                                            {
                                                //if (globaldata.startflag) //&& globaldata.m_pcbuffer.gcpcinfo.pcfileinfo.cur_DataName != null)
                                                {
                                                    timePoint.Add(((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Save_Port2[i]).ctimer);
                                                    listPoint.Add(dvalue);
                                                    saveflag = true;
                                                }
                                            }

                                        }
                                    }
                                    globaldata.m_signalbuffer.Save_Port2.Clear();
                                }
                                else
                                {
                                    listPoint.Clear();
                                    timePoint.Clear();
                                    //Console.WriteLine("等待开始按钮!");
                                    if (!globaldata.startflag)
                                    {
                                        globaldata.m_signalbuffer.Save_Port2.Clear();
                                    }
                                    else
                                    {
                                        starttimer = ((SignalBuffer.Channel_XY)globaldata.m_signalbuffer.Save_Port2[0]).ctimer;
                                    }
                                }


                            }
                        }
                    }

                    if (globaldata.cancelflag2)
                    {
                        if (this.savefilename != null)
                        {
                            if (File.Exists(this.savefilename))
                            {
                                File.Delete(this.savefilename);
                            }
                        }
                        globaldata.cancelflag2 = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("Channel 2 Data Save Crash!");
                Log.Error(ex.Message);
            }

        }
        #endregion



        private void ChannelDataReStart()
        {
            try
            {
                t_DataSave = null;
                if (datamre != null)
                {
                    datamre.Reset();
                }

                t_DataSave = new Thread(Monitor_Data);
                t_DataSave.IsBackground = true;
                t_DataSave.Start();
            }
            catch
            {
                Log.Error("Channel 2 Data Save Thread Restart Crash!");
            }
        }

        public void ChannelDataStart()
        {
            if( datamre != null)
            {
                datamre.Reset();
            }
            t_DataSave = new Thread(Monitor_Data);
            t_DataSave.IsBackground = true;
            t_DataSave.Start();
        }

        public void ChannelDataStop()
        {
            datamre.Set();
        }


    }
}
