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.IO.Ports;

namespace WindowsFormsApp1
{
    public partial class ConfigureApp : Form
    {
        String[] ports;
        String inputStr;
        bool isConnected = false;
        SerialPort port;
        public ConfigureApp()
        {
            InitializeComponent();
            controls.Enabled = false;
            numericUpDownsDefault();
            ports = SerialPort.GetPortNames();

            for (int i = 0; i < ports.Length; i++)
            {
                Console.WriteLine(ports[i]);
                comboBoxPorts.Items.Add(ports[i]);
            }
        }

        private void buttonSerial_Click(object sender, EventArgs e)
        {
            if (!isConnected && serialSelected())
                connectToArduino();

            else if (isConnected && serialSelected())
                disconnectFromArduino();
            else
                MessageBox.Show("Serial port not selected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        private void connectToArduino()
        {
            string selectedPort = comboBoxPorts.GetItemText(comboBoxPorts.SelectedItem);
            port = new SerialPort(selectedPort, 9600, Parity.None, 8, StopBits.One);
            port.Open();
            if (Ping())
            {
                buttonSerial.Text = "Disconnect";
                controls.Enabled = true;
                comboBoxPorts.Enabled = false;
                isConnected = true;
            }
            else
            {
                MessageBox.Show("Simulator is not connected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                disconnectFromArduino();
            }
                
           
        }

        private void disconnectFromArduino()
        {
            isConnected = false;
            port.Write("[DISSCONECTED]");
            port.Close();
            buttonSerial.Text = "Connect";
            controls.Enabled = false;
            comboBoxPorts.Enabled = true;
        }

        private void buttonWrite_Click(object sender, EventArgs e)
        {

            if (MessageBox.Show("Do you want to save values to simulator and close application?", "Save and Close", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
            {
                if (Ping())
                {
                    //all textBox values to string format
                    string text = '[' + numericUpDown1.Value.ToString() + ';' + numericUpDown2.Value.ToString() + ';' + numericUpDown3.Value.ToString() + ';'
                                      + numericUpDown4.Value.ToString() + ';' + numericUpDown5.Value.ToString() + ';' + numericUpDown6.Value.ToString() + ';'
                                      + numericUpDown7.Value.ToString() + ';' + numericUpDown8.Value.ToString() + ';' + numericUpDown9.Value.ToString() + ';'
                                      + numericUpDown10.Value.ToString() + ';' + numericUpDown11.Value.ToString() +  ']';
                    port.Write(text);
                    port.Write("[DISSCONECTED]");
                    port.Close();
                    System.Windows.Forms.Application.Exit();
                }
                else
                {
                    MessageBox.Show("Simulator is not connected! Restart configuration application.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    disconnectFromArduino();
                    port.Close();
                    System.Windows.Forms.Application.Exit();
                }
                
            }

        }
        private void numericUpDownsDefault()
        {
            numericUpDown1.Value = 40;
            numericUpDown2.Value = 30;
            numericUpDown3.Value = 30;
            numericUpDown4.Value = 200;
            numericUpDown5.Value = 0;
            numericUpDown6.Value = 20;
            numericUpDown7.Value = 20;
            numericUpDown8.Value = 180;
            numericUpDown9.Value = 10000;
            numericUpDown10.Value = 10000;
            numericUpDown11.Value = 50;
        }

        private bool serialSelected()
        {
            return !String.IsNullOrWhiteSpace(comboBoxPorts.Text);
        }

        private bool Ping()
        {
            port.Write("[PING]");

            inputStr = port.ReadExisting();
            int time = 0;
            while(time < 2000)
            {
                if (inputStr.Equals("[PONG]"))
                    break;
                else
                {
                    time += 50;
                    inputStr = port.ReadExisting();
                    Console.WriteLine("input string is: " + inputStr);
                    System.Threading.Thread.Sleep(50);
                }
                                    
            }
            
            if (inputStr.Equals("[PONG]"))
            {
                Console.WriteLine("Succes/n");
                return true;
            }
            else
            {
                Console.WriteLine("No reply/n");
                return false;
            }
        }
    }
}
