using Arction.Wpf.Charting;
using Arction.Wpf.Charting.Axes;
using Arction.Wpf.Charting.SeriesXY;
using Arction.Wpf.Charting.Views.ViewXY;
using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace StartServerWPF.Modules.MseedChart.Models
{
    public class WavesModel
    {
        public List<AxisY> CreateYAxisChart(List<StationModel> stationModels, LightningChart curChart)
        {
            List<AxisY> axisYList = new List<AxisY>();                
            foreach (var item in stationModels)
            {
                int distancetoX= SetYasixPlacement(curChart);
                AxisY axisY = new AxisY(curChart.ViewXY);
                //添加Z分量波形
                if (item.dz.Count > 0)
                {
                    axisY.SetRange(0, 100);
                }
                axisY.Title.Text = string.Format("{0}.Z", item.Name);
                axisY.Title.DistanceToAxis = distancetoX;
                axisYList.Add(axisY);
                //添加N分量波形
                axisY = new AxisY(curChart.ViewXY);
                if (item.dn.Count > 0)
                {
                    axisY.SetRange(0, 100);
                }
                axisY.Title.Text = string.Format("{0}.N", item.Name);
                axisY.Title.DistanceToAxis = distancetoX;
                axisYList.Add(axisY);

                //添加E分量波形
                 axisY = new AxisY(curChart.ViewXY);
                if (item.de.Count > 0)
                {
                    axisY.SetRange(0, 100);
                }          
                axisY.Title.Text = string.Format("{0}.E", item.Name);
                axisY.Title.DistanceToAxis = distancetoX;
                axisYList.Add(axisY);

            }
            return axisYList;
        }
        public int SetYasixPlacement(LightningChart chart)
        {
            int distancetoX = 0;
            if (chart.ViewXY.AxisLayout.YAxisAutoPlacement == YAxisAutoPlacement.AllLeft)
            {
                distancetoX = -(int)chart.ActualWidth + 70;
            }
            else if (chart.ViewXY.AxisLayout.YAxisAutoPlacement == YAxisAutoPlacement.AllRight)
            {
                distancetoX = (int)chart.ActualWidth-2*60;
            }
            return distancetoX;
        }

        public List<AxisY> CreateAxisYEventTime(StationEventJson stationEventJson, ViewXY chartV, List<StationModel> stationModels)
        {
            for (int i = 0; i < stationEventJson.phases.Count; i++)
            {
                phases ph= stationEventJson.phases[i];
                var index=  stationModels.FindIndex(a =>ph.id.Contains(a.Name));
                if(index == -1)
                {
                    continue;
                }
                int assignYAxisIndex = index * 3;
                LineCollection lineCollection = new LineCollection()
                {
                    AssignXAxisIndex = 0,
                    AssignYAxisIndex = assignYAxisIndex,
                    Tag=ph.id,    //用于排序otime,只需要排更SHZ通道
                    Lines = new SegmentLine[] { new SegmentLine(chartV.XAxes[0].DateTimeToAxisValue(ph.atime), chartV.YAxes[assignYAxisIndex].Minimum, chartV.XAxes[0].DateTimeToAxisValue(ph.atime), chartV.YAxes[assignYAxisIndex].Maximum) },
                    ShowInLegendBox = false
                };
                
                lineCollection.LineStyle.Color = System.Windows.Media.Colors.Red;
                lineCollection.Title.Text = chartV.YAxes[assignYAxisIndex].Title.Text + ph.atime.ToString();
                lineCollection.Title.Visible = true;
                lineCollection.Title.Font.Size = 10;
                lineCollection.Title.Shadow.DropColor = System.Windows.Media.Colors.Transparent;
                //lineCollection.Title.Shadow.ContrastColor = System.Windows.Media.Colors.Transparent;
                lineCollection.Title.AutoPlacement = false;
                lineCollection.Title.HorizontalAlign = AlignmentHorizontal.Left;
                var b = chartV.XAxes[0].ValueToCoordD(chartV.XAxes[0].DateTimeToAxisValue(ph.atime))-80;
                lineCollection.Title.Offset.SetValues((int)b, 3);
                lineCollection.Title.Color = System.Windows.Media.Colors.Red;
                chartV.LineCollections.Add(lineCollection);
            }

            for (int i = 0; i < stationEventJson.amps.Count; i++)
            {
                amps am = stationEventJson.amps[i];
                var index = stationModels.FindIndex(a => am.id.Contains(a.Name));
                if (index == -1)
                {
                    continue;
                }
                int assignYAxisIndex = index * 3;
                assignYAxisIndex = am.id.Contains("SHN") ? assignYAxisIndex + 1 : assignYAxisIndex + 2;
                LineCollection lineCollection = new LineCollection()
                {
                    AssignXAxisIndex = 0,
                    AssignYAxisIndex = assignYAxisIndex,
                    Lines = new SegmentLine[] { new SegmentLine(chartV.XAxes[0].DateTimeToAxisValue(am.atime), chartV.YAxes[assignYAxisIndex].Minimum, chartV.XAxes[0].DateTimeToAxisValue(am.atime), chartV.YAxes[assignYAxisIndex].Maximum) },
                    ShowInLegendBox = false
                };
                lineCollection.LineStyle.Color = System.Windows.Media.Colors.Red;
                lineCollection.Title.Text = chartV.YAxes[assignYAxisIndex].Title.Text+ " "+ am.atime.ToString("HH:mm:ss.fff");
                lineCollection.Title.Visible = true;
                lineCollection.Title.Font.Size = 10;
                lineCollection.Title.Shadow.DropColor = System.Windows.Media.Colors.Transparent;
               // lineCollection.Title.Shadow.ContrastColor = System.Windows.Media.Colors.Transparent;
                lineCollection.Title.AutoPlacement = false;
                lineCollection.Title.HorizontalAlign = AlignmentHorizontal.Left;
                var b=  chartV.XAxes[0].ValueToCoordD(chartV.XAxes[0].DateTimeToAxisValue(am.atime))-80;
                lineCollection.Title.Offset.SetValues((int)b,3);
                lineCollection.Title.Color = System.Windows.Media.Colors.Red;
                chartV.LineCollections.Add(lineCollection);
            }
            return new List<AxisY>();
        }


        public ConcurrentQueue<StationModel> ReadMseedFile(string dataFilePath, string asciiSavePath, bool isMultFile = false)
        {
            if (!Directory.Exists(Path.GetDirectoryName(dataFilePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(dataFilePath));
            }
            if (!Directory.Exists(Path.GetDirectoryName(asciiSavePath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(asciiSavePath));
            }
            ConcurrentQueue<StationModel> smList = new ConcurrentQueue<StationModel>();
            Stopwatch sw = Stopwatch.StartNew();
            if (isMultFile)
            {
                var filePath = new DirectoryInfo(Path.GetDirectoryName(dataFilePath));
                FileInfo[] files = filePath.GetFiles();
                var mseedFiles = files.Where(i => i.Extension == ".mseed");

                var asciiFiles = new DirectoryInfo(Path.GetDirectoryName(asciiSavePath));
                var asciifile = asciiFiles.GetFiles();
                if (asciifile.Count() == 0)
                {
                    foreach(var item in mseedFiles)
                    {
                        var buffer= File.ReadAllBytes(item.FullName);
                        Mseed2asciiApi.bufferMseedData(buffer.Length, buffer);
                     //   MSeed2Asc(item.FullName, Path.Combine(Path.GetDirectoryName(asciiSavePath), Path.GetFileNameWithoutExtension(item.Name)));
                    };

                }
                // 并行运算
                //  Parallel.ForEach(asciiFiles.GetFiles(), (item) =>
                //  {
                //   var list = UpdateWavesFromTxt(item.FullName);
                // list.ForEach(i => smList.Enqueue(i));
                // });
                var list = UpdateWavesFromTxt(asciiSavePath);
                list.ForEach(i => smList.Enqueue(i));
            }
            else
            {
                if (!File.Exists(asciiSavePath))
                {
                   // MSeed2Asc(dataFilePath, asciiSavePath);
                }
                var buffer = File.ReadAllBytes(dataFilePath);
                Mseed2asciiApi.bufferMseedData(buffer.Length, buffer);

             //   var list = UpdateWavesFromTxt(asciiSavePath);
            //    list.ForEach(i => smList.Enqueue(i));
            }
            sw.Stop();
            Debug.WriteLine("MSeed2Asc解压时间：" + sw.Elapsed.TotalSeconds);
            return smList;
        }
        public List<StationModel> UpdateWavesFromMseedC(string data)
        {
            List<StationModel> temSM = new List<StationModel>();

            if (data.Length > 0)
            {
                int channelFlag = 0;
                string row = data.Trim();
                StationModel station = new StationModel();
                if (data.Contains("HA"))
                {
                    string[] rowStr = data.Split(',');
                    string chnStr1 = rowStr[0].Substring(21, 3);
                    string stationName = rowStr[0].Substring(14, 3);
                    if (!temSM.Any(name => name.Name == stationName))
                    {
                        station = new StationModel();
                        station.Name = stationName;
                        station.BeginTime = Convert.ToDateTime(rowStr[3]).AddHours(8);
                        station.PointCount = int.Parse(rowStr[1].Trim().Split(' ')[0]);
                        station.SamplingFrequency = int.Parse(rowStr[2].Trim().Split(' ')[0]);
                        temSM.Add(station);
                    }
                    channelFlag = (chnStr1 == "SHZ") ? 0 : (chnStr1 == "SHN") ? 1 : 2;
                }
                else
                {
                    switch (channelFlag)
                    {
                        case 0://Z
                            station.dz.Add(double.Parse(row));
                            break;
                        case 1://N
                            station.dn.Add(double.Parse(row));
                            break;
                        case 2://E
                            station.de.Add(double.Parse(row));
                            break;
                    }
                }
                // temSM.Add(station);
             //   temSM.Reverse();
            }
            return temSM;
        }

        public List<StationModel> UpdateWavesFromTxt(string fn)
        {
            string allStr;
            List<StationModel> temSM = new List<StationModel>();
            using (StreamReader streamReader = new StreamReader(fn))
            {
                allStr = streamReader.ReadToEnd();
            }
            if (allStr.Length > 0)
            {
                string[] strLines = allStr.Trim().Split(new char[] { '\n' });
              //  List<string> strList = strLines.ToList();
              //  int cnt = strList.Count;
              //  string[] snStr = strLines[0].Trim().Split(',');
               // string tmpName = snStr[0].Substring(14, 3);
                StationModel station = new StationModel();
              //  station.Name = tmpName;

                int channelFlag = 0;

                for (int i = 0; i < strLines.Length; i++)
                {
                    string row = strLines[i].Trim();
                    if (strLines[i].Contains("HA"))
                    {
                        string[] rowStr = strLines[i].Split(',');
                        string chnStr1 = rowStr[0].Substring(21, 3);
                        string stationName = rowStr[0].Substring(14, 3);
                        if (!temSM.Any(name => name.Name == stationName))
                        {
                            station = new StationModel();
                            station.Name = stationName;
                            station.BeginTime = Convert.ToDateTime(rowStr[3]).AddHours(8);
                            station.PointCount = int.Parse(rowStr[1].Trim().Split(' ')[0]);
                            station.SamplingFrequency = int.Parse(rowStr[2].Trim().Split(' ')[0]);
                            temSM.Add(station);
                        }
                        channelFlag = (chnStr1 == "SHZ") ? 0 : (chnStr1 == "SHN") ? 1 : 2;
                    }
                    else
                    {
                        switch (channelFlag)
                        {
                            case 0://Z
                                station.dz.Add(double.Parse(row));
                                break;
                            case 1://N
                                station.dn.Add(double.Parse(row));
                                break;
                            case 2://E
                                station.de.Add(double.Parse(row));
                                break;
                        }
                    }
                }
                // temSM.Add(station);
                temSM.Reverse();
            }
            return temSM;
        }
         
        public void MSeed2Asc(string filePath, string savePath)
        {
            using (Process compiler = new Process())
            {
                compiler.StartInfo.FileName = "mseed2ascii.exe";
                compiler.StartInfo.Arguments = filePath + " -o " + savePath;
                compiler.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                compiler.StartInfo.CreateNoWindow = true;
                compiler.Start();
                compiler.WaitForExit();
            }
        }

        public StationEventJson ReadChartJsonFile(string jsonFile)
        {
            if (File.Exists(jsonFile))
            {
                var str = File.ReadAllText(jsonFile);
                var st = JsonConvert.DeserializeObject<StationEventJson[]>(str);

                StationEventJson jsonST = st[0];
                return jsonST;
            }
            return null;

        }



        #region  实时数据解析

        public ConcurrentQueue<StationModel> ReadWavesFromJson(string[] stations)
        {
            ConcurrentQueue<StationModel> temSM = new ConcurrentQueue<StationModel>();

             StationModel station = new StationModel();

            for (int i = 0; i < stations.Length; i++)
            {
                station = new StationModel();
                station.Name = stations[i].Trim();
                station.dz.Add(0);
                station.dn.Add(0);
                station.de.Add(0);
                temSM.Enqueue(station);
            }

           temSM.Reverse();
            return temSM;
        }
        #endregion
    }
}
