import processing.serial.*;

Serial port;

int x = 512;
int y = 512;
int Switch = 0;
PFont f;
String value;

// Smoothing
float smoothX = 256;
float smoothY = 256;

void setup() {
  size(512, 512);
  println("Available Ports:");
  println(Serial.list());

  String portName = Serial.list()[0]; // Change if needed
  port = new Serial(this, portName, 9600);
  port.bufferUntil('\n');

  f = createFont("Arial", 16, true);
  textFont(f, 16);
}

void draw() {
  fill(0);
  fill(255);

  // Smooth the analog input
  smoothX = lerp(smoothX, map(x, 0, 1023, 0, width), 0.1);
  smoothY = lerp(smoothY, map(y, 0, 1023, 0, height), 0.1);

  // Clamp values to avoid going outside canvas
  float cx = constrain(smoothX, 0, width);
  float cy = constrain(smoothY, 0, height);

  // Draw circle
  if (Switch == 1) {
    fill(0, 255, 0); // Green when pressed
    ellipse(cx, cy, 100, 100);
  } else {
    fill(255); // White otherwise
    ellipse(cx, cy, 25, 25);
  }

  fill(255);
  text("AnalogX = " + x + " | AnalogY = " + y, 10, 20);
}

void serialEvent(Serial port) {
  value = port.readStringUntil('\n');

  if (value != null) {
    value = trim(value);
    println("Serial: " + value);

    try {
      int[] values = int(splitTokens(value, ","));
      if (values.length == 3) {
        x = values[0];
        y = values[1];
        Switch = values[2];
      }
    } catch (Exception e) {
      println("Error parsing: " + value);
    }
  }
}
