using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;

public class ArduinoConnector : MonoBehaviour {

    // the port the Arduino controller is connected to
    public string Port;
    // the serial port instance we use to send data
    private static SerialPort serialPort;
    // the actual values that we want to send
    private int value1 = -1;
    private int value2 = -1;
    private int value3 = -1;
    private int value4 = -1;
    private int value5 = -1;
    // initialization is done here: the port is set up and the connection is opened
    void Awake()
    {
        // create the port with a baudrate of 9600
        ArduinoConnector.serialPort = new SerialPort(Port, 9600);
        // open up the actual connection
        this.OpenConnection();
    }

    // opens the connection to the serial port
    public void OpenConnection()
    {
        if (ArduinoConnector.serialPort != null)
        {
            if (ArduinoConnector.serialPort.IsOpen)
            {
                ArduinoConnector.serialPort.Close();
                UnityEngine.Debug.Log("closing port, because it was already open...");
            }
            else
            {
                ArduinoConnector.serialPort.Open();
                ArduinoConnector.serialPort.ReadTimeout = 16;
                UnityEngine.Debug.Log("port opened...");
            }
        }
        else
        {
            if (ArduinoConnector.serialPort.IsOpen)
            {
                UnityEngine.Debug.Log("port is already open...");
            }
            else
            {
                UnityEngine.Debug.Log("port is null...");
            }
        }
    }
    // when terminating the application, we deactivate all motors
    void OnApplicationQuit()
    {
        string output = "0,0,0,0,0\n";
        ArduinoConnector.serialPort.Write(output);
        ArduinoConnector.serialPort.Close();
    }
    // we send the data, that is the slider values from the UI
    public void sendData(int val1, int val2, int val3, int val4, int val5)
    {
        if (value1 != val1 || value2 != val2 || value3 != val3 || value4 != val4 || value5 != val5)
        {
            value1 = val1;
            value2 = val2;
            value3 = val3;
            value4 = val4;
            value5 = val5;
            string output = value1.ToString() + "," + value2.ToString() + "," + value3.ToString() + "," + value4.ToString() + "," + value5.ToString() + "\n";
            UnityEngine.Debug.Log("change motor activation to: " + value1.ToString() + "," + value2.ToString() + "," + value3.ToString() + "," + value4.ToString() + "," + value5.ToString() + "...");
            ArduinoConnector.serialPort.Write(output);
        }
    }
}
