import mqtt.*;
import processing.serial.*;

Serial myPort;

PFont f;
PFont fb;

MQTTClient client;

String location = "Oulu";
String s = "";

void setup() {
  size(640, 360);
  background(159, 234, 254);
  
  f = createFont("Times-Roman", 24);
  fb = createFont("Times-Bold", 48);
  textAlign(CENTER, CENTER);
  
  client = new MQTTClient(this);
  client.connect("mqtt://public:public@public.cloud.shiftr.io", "processing");
  client.subscribe("fab22");
  
  myPort = new Serial(this, Serial.list()[0], 9600);
}

void draw() {
  background(159, 234, 254);
  
  // Check for button presses coming in from the board, relay character through MQTT
  if(myPort.available() > 0){
    client.publish("fab22", location + ": " + str(myPort.read()));
  }
  
  // print the prompt
  textFont(f);
  fill(33, 96, 251);
  text("press a key", 320, 100);
  
  // print a received message
  textFont(fb);
  String[] list = split(s,':');
  if(list[0].equals(location) == true){
    fill(79, 33, 251);
  } else {
    fill(251, 33, 96);
  }
  text(s, 320, 200);
}

void keyPressed() {
  if(key == ' '){
    client.publish("fab22", location + ": SPACE");
  } else {
    client.publish("fab22", location + ": " + str(key));
  }
}

void messageReceived(String topic, byte[] payload) {
  s = new String(payload);
}
