#include <Arduino_MKRIoTCarrier.h>
#include <WiFiNINA.h>
#include <ArduinoMqttClient.h>
#include "state.h"
#include "motor.h"
#include "secrets.h"

MKRIoTCarrier carrier;
WiFiSSLClient wifi_client;
MqttClient mqtt_client(wifi_client);

//motor control variables
int motor_count = 0;
int motor_count_max = 64;

uint32_t green_led_color = carrier.leds.Color(0, 255, 0);

void setup()
{
	Serial.begin(9600);

	Serial.println("Started");

	carrier.noCase();
	carrier.begin();

	carrier.display.init(240, 240);

	motor_setup();

	pinMode(TFT_BACKLIGHT, OUTPUT);
	digitalWrite(TFT_BACKLIGHT, HIGH);

	change_state(STATE_CONNECTING);

	Serial.println("Connecting to WiFi...");

	if (wifi_enterprise) WiFi.beginEnterprise(wifi_ssid, wifi_username, wifi_password);
	else WiFi.begin(wifi_ssid, wifi_password);

	while (WiFi.status() != WL_CONNECTED) delay(1000);

	Serial.println("Connected to WiFi, connecting to MQTT...");

	mqtt_client.setUsernamePassword(mqtt_username, mqtt_password);
	if (!mqtt_client.connect(mqtt_server, 8883)) {
		Serial.print("MQTT connection failed with error code: ");
		Serial.println(mqtt_client.connectError());
		return;
	}

	Serial.println("Connected to MQTT");

	carrier.Buzzer.beep();

	mqtt_client.subscribe("dispense");

	change_state(STATE_LOGGED_OUT);
}

void loop()
{
	carrier.Buttons.update();

	// Rotate motor if needed
	if (motor_count) {
		motor_clockwise();
		motor_count--;
	}

	// Receive MQTT messages
	int message_size = mqtt_client.parseMessage();
	if (message_size) {
		Serial.print("Got message with topic: ");
		Serial.println(mqtt_client.messageTopic());

		if (mqtt_client.messageTopic() == "dispense") {
			Serial.println("Dispensing...");

			// Start rotating motor
			motor_count = motor_count_max;
		}
	}

	loop_state();

	delay(50);
}
