using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
using System.Globalization;
using System.Windows.Forms.DataVisualization.Charting;


namespace XYform
{
    public partial class MainWindow : Form
    {
        static Socket socket;
        string logs = "log";
        bool measurerun;
        System.Windows.Forms.Timer Timer1 = new System.Windows.Forms.Timer();
        
        string path = "log.txt";
        Series seriesXY = new Series
        {
            Name = "posXY",
            Color = System.Drawing.Color.Red,
            IsVisibleInLegend = false,
            IsXValueIndexed = false,
            ChartType = SeriesChartType.Line,
        };

        byte[] bytesReceived = new byte[256];
        int bytes = 0;
        string dat2;
        string dat;
        string[] pos;
        float x = 0;
        float y = 0;
        string[] resultString;

        System.IO.StreamWriter file;
        ContextMenu cm_graph = new ContextMenu();
           
        public MainWindow()
        {
            InitializeComponent();
            this.Text = "Odometry";
           
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Timer1.Tick += new EventHandler(Timer1_Tick);
            Timer1.Interval = 40;
            start.Enabled = false;
            Reset.Enabled = false;
            
                file = new System.IO.StreamWriter(path, true);
            
            
            measurerun = false;
            graph_XY.Series.Clear();
            graph_XY.Series.Add(seriesXY);
            graph_XY.Series[0].Points.Add();
            graph_XY.Series[0].Points[0].IsEmpty = true;
            

            graph_XY.ChartAreas[0].AxisX.Maximum = 0.4;
            graph_XY.ChartAreas[0].AxisX.Minimum = -0.4;
            graph_XY.ChartAreas[0].AxisY.Minimum = -0.4;
            graph_XY.ChartAreas[0].AxisY.Maximum = 0.4;
            graph_XY.ChartAreas[0].AxisX.Crossing = 0;
            graph_XY.ChartAreas[0].AxisY.Crossing = 0;
            graph_XY.ChartAreas[0].AxisX.Interval = 0.1;
            graph_XY.ChartAreas[0].AxisY.Interval = 0.1;
            graph_XY.ChartAreas[0].AxisX.MajorGrid.LineDashStyle= ChartDashStyle.Dot;
            graph_XY.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot;
            graph_XY.ChartAreas[0].AxisY.IsLabelAutoFit = true;
            graph_XY.ChartAreas[0].AxisX.IsLabelAutoFit = true;
            graph_XY.ChartAreas[0].AxisX.Title = " Y [m]";
            graph_XY.ChartAreas[0].AxisY.TextOrientation = TextOrientation.Horizontal;
            graph_XY.ChartAreas[0].AxisY.Title = " X [m]";

            graph_XY.ContextMenu = cm_graph;

            cm_graph.MenuItems.Add("Save", new EventHandler(SaveGraph_Click));
            

            if (!Directory.Exists(logs))
            {
                Directory.CreateDirectory(logs);
            }

            Directory.SetCurrentDirectory(Path.Combine(Directory.GetCurrentDirectory(), logs));

            


        }

        private void Timer1_Tick(object sender, EventArgs e)
        {

            
            if (socket.Available > 0)
            {

                // The following will block until te page is transmitted.
                //while (socket.Available > 0)
                //{


                bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
                dat = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
                dat2 = Regex.Replace(dat, "\0", "");
                pos = dat2.Split('\r');



                foreach (string s in pos)
                {
                    display.AppendText(s);
                    if (measurerun == true)
                    {
                        file.Write(s);



                        if (s.Length > 20)
                        {
                            if (s[0] == 'X')
                            {
                                resultString = s.Split(' ');
                                x = float.Parse(resultString[1], CultureInfo.InvariantCulture);
                                y = float.Parse(resultString[3], CultureInfo.InvariantCulture);
                                if (x > graph_XY.ChartAreas[0].AxisX.Maximum) graph_XY.ChartAreas[0].AxisX.Maximum = Math.Round(x + 0.25 * x, 1);
                                if (x < graph_XY.ChartAreas[0].AxisX.Minimum) graph_XY.ChartAreas[0].AxisX.Minimum = Math.Round(x + 0.25 * x, 1);
                                if (y > graph_XY.ChartAreas[0].AxisY.Maximum) graph_XY.ChartAreas[0].AxisY.Maximum = Math.Round(y + 0.25 * y, 1);
                                if (y < graph_XY.ChartAreas[0].AxisY.Minimum) graph_XY.ChartAreas[0].AxisY.Minimum = Math.Round(y + 0.25 * y, 1);
                                seriesXY.Points.AddXY(x, y);

                            }
                        }

                    }


                }




                //}




            }


        }

        private void SaveGraph_Click(object sender, EventArgs e)
        {
            
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "PNG (*.png)|*.png";
            saveFileDialog1.FilterIndex = 2;
            saveFileDialog1.RestoreDirectory = true;
            saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
            //saveFileDialog1.ShowDialog();
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                graph_XY.SaveImage(saveFileDialog1.FileName, ChartImageFormat.Png);
            }

        }



        private void connect_Click(object sender, EventArgs e)
        {
           
                try
                {
                    socket.Connect(IPAddress.Parse("192.168.100.1"), 9876);
                    display.Text = "Pripojeno!";
                    display.Text += System.Environment.NewLine;
                    Timer1.Start();
                    start.Enabled = true;
                    Reset.Enabled = true;
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message.ToString(), "Chyba site", MessageBoxButtons.OK, MessageBoxIcon.Error);


                }
            
           
            

        }

        private void start_Click(object sender, EventArgs e)
        {
            if (measurerun == false)
            {
                byte[] bytesToSend = Encoding.ASCII.GetBytes("start\r");
                socket.Send(bytesToSend);
                path = DateTime.Now.ToString("hh-mm_dd-MM-yyyy", CultureInfo.InvariantCulture);
                path = path + ".txt";
                file = new System.IO.StreamWriter(path, true);
                measurerun = true;
                start.Text = "Stop";
            }
            else
            {
                byte[] bytesToSend = Encoding.ASCII.GetBytes("stopt\r");
                socket.Send(bytesToSend);
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "txt (*.txt)|*.txt";
                saveFileDialog1.FilterIndex = 2;
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.InitialDirectory = Directory.GetCurrentDirectory();
                //saveFileDialog1.ShowDialog();
                file.Dispose();
                measurerun = false;
                DialogResult dialogResult = MessageBox.Show("Save", "Save measurement", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        File.Copy(path, saveFileDialog1.FileName.ToString(),false);
                    }
                    catch(Exception exp)
                    {

                        MessageBox.Show(exp.Message.ToString(), "Chyba ulozeni", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    }
                }
                }
                else if (dialogResult == DialogResult.No)
                {
                    
                }
                
                
                start.Text = "Start";
            }
        }

        

        private void Reset_Click(object sender, EventArgs e)
        {
            graph_XY.Series[0].Points.Clear();
            byte[] bytesToSend = Encoding.ASCII.GetBytes("reset\r");
            socket.Send(bytesToSend);
            measurerun = false;
            file.Dispose();
            start.Text = "Start";
            display.Clear();
            graph_XY.ChartAreas[0].AxisX.Maximum = 0.4;
            graph_XY.ChartAreas[0].AxisX.Minimum = -0.4;
            graph_XY.ChartAreas[0].AxisY.Minimum = -0.4;
            graph_XY.ChartAreas[0].AxisY.Maximum = 0.4;
            graph_XY.Series[0].Points.Add();
            graph_XY.Series[0].Points[0].IsEmpty = true;
        }
    }
}
