#import <WiFiClientSecure.h>
#import <PubSubClient.h>
#import <ArduinoJson.h>

#import "wifi.h"
#import "mqtt.h"
#import "event.h"

#import "config.h";
#import "secrets.h";

WiFiClientSecure esp_client;
PubSubClient mqtt_client(esp_client);

unsigned long last_msg = 0;
#define MSG_BUFFER_SIZE 50
char msg[MSG_BUFFER_SIZE];

void mqttCallback(char *topic, byte* payload, unsigned int length) {
  String message_in = "";
  for (int i = 0; i < length; i++) {
    message_in += (char)payload[i];
  }

  JsonDocument doc;
  deserializeJson(doc, message_in);
  const char* event_type = doc["type"];
  
  IEventHandler* handler = get_event_handler(event_type);
  handler->handle(doc["data"].as<JsonObject>());
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);

  connectToWiFi(wifi_ssid, wifi_password);

  esp_client.setCACert(root_ca);
  mqtt_client.setServer(mqtt_server, mqtt_port);
  mqtt_client.setCallback(mqttCallback);

  Serial.println("Hello, ESP32-S2!");
}

void loop() {
  reconnectToMQTT(&mqtt_client, mqtt_username, mqtt_password, mqtt_client_id, mqtt_topic);
  mqtt_client.loop();
  // put your main code here, to run repeatedly:
  delay(100); // this speeds up the simulation
}