using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.IO.Ports;

public class espwrite : MonoBehaviour
{

    // public GameObject Thumb;
    public GameObject Index;

    [SerializeField] private string portName = "COM21";
    
    string portName_;
    SerialPort ESP32_port;

    double time;

    [Header("Interaction Values")]

    public double index_val;

    [Range(0.035f, 1f)]
    public double timeDelay = 0.045f;

    [Header("Index thimble management")]


    [SerializeField]
    private int idx_min = 36;

    [SerializeField]
    public int idx_lim = 200;

    [Range(0, 100)]
    public int idx_offset = 0;

    byte[] outBuffer = new byte[1];
    // Start is called before the first frame update
    void Start()
    {
        portName_ = portName;
        ESP32_port = new SerialPort(portName, 115200);
        ESP32_port.Open();
        time = 0f;
        timeDelay = 0.045f;

        // Routine for the initialization of the device
        Serial_Data_Write(idx_min + 50);
        System.Threading.Thread.Sleep(500);
        Serial_Data_Write(idx_min);
    }

    // Update is called once per frame
    void Update()
    {
        time = time + 1f * Time.deltaTime;
        if(time >= timeDelay)
        {
            time = 0f;

            index_val = Index.GetComponent<fingertip_interaction_manager>().getDisplacement();

            if (index_val > this.transform.localScale.x)
                index_val = this.transform.localScale.x;

            index_val = map(index_val , 0, this.transform.localScale.x, 36 + idx_offset, idx_lim);

            int index_val_int = System.Convert.ToInt32(System.Math.Round(index_val));
           
            Serial_Data_Write(index_val_int);
           
        }

    }

    // Function called repeatedly
    void Serial_Data_Write(int motor_idx_val)
    {
        if (ESP32_port.IsOpen)
        {
            outBuffer[0] = System.Convert.ToByte(motor_idx_val);
            // outBuffer[1] = System.Convert.ToByte(motor_plx_val);
            ESP32_port.Write(outBuffer, 0, outBuffer.Length);
        }
    }

    double map(double s, double a1, double a2, double b1, double b2)
    {
        return b1 + (s - a1) * (b2 - b1) / (a2 - a1);
    }

    void OnApplicationQuit()
    {
        Debug.Log("Application ending after " + Time.time + " seconds");
        Serial_Data_Write(idx_min);
        ESP32_port.Close();
    }
}
