#include <PubSubClient.h>
// MQTT: ID, server IP, port, username and password

//const String MQTT_CLIENT_ID = "matrix_client_" + String(random(0xffff), HEX);
const char *MQTT_SERVER_IP = "192.168.1.105";
const uint16_t MQTT_SERVER_PORT = 1883;
const char *MQTT_USER = "mdchaparror";
const char *MQTT_PASSWORD = "un80187452";
const char *MQTT_TOPIC_FULL = "matrix/full";
DynamicJsonDocument doc(300);

WiFiClient wifiClient;
PubSubClient client(wifiClient);

void callback(char *p_topic, byte *p_payload, unsigned int p_length)
{
  // concat the payload into a string
  
  String payload;
  for (uint8_t i = 0; i < p_length; i++)
  {
    payload.concat((char)p_payload[i]);
  }

  if (String(MQTT_TOPIC_FULL).equals(p_topic))
  {

    yield();
    DeserializationError err = deserializeJson(doc, String(payload));
    yield();
    // if (err)
    // {
    //   Serial.print(F("deserializeJson() failed with code "));
    //   Serial.println(err.c_str());
    // }
    mensaje = doc["msg"].as<String>();
    R = doc["R"];
    G = doc["G"];
    B = doc["B"];
    texto = mensaje + " " + hora;
    x = matrix.width();
    longitud = texto.length() * 5 + 64;
  }
}

void reconnect()
{
  while (!client.connected())
  {
    String clientId = "matrix_client-" + String(random(0xffff), HEX);
    if (client.connect(clientId.c_str(), MQTT_USER, MQTT_PASSWORD))
    {
      //Serial.println("INFO: connected");
      client.subscribe(MQTT_TOPIC_FULL);
    }
    else
    {
      //Serial.print("ERROR: failed, rc=");
      //Serial.print(client.state());
      //Serial.println("DEBUG: try again in 5 seconds");
      yield();
      delay(1000);
    }
    
  }
}

void mqtt_init()
{
  client.setServer(MQTT_SERVER_IP, MQTT_SERVER_PORT);
  client.setCallback(callback);
}

