#include "Stab_config.h"

void readMQTTSettings() { // Чтение параметров MQTT
  EEPROM.begin(EEPROM_SIZE);
  if (EEPROM.read(MQTT_SAVED_FLAG_ADDR) == MQTT_SAVED_FLAG_VALUE) {
  mqtt_server = readEEPROM(MQTT_SERVER_ADDR, 32);
  EEPROM.get(MQTT_PORT_ADDR,mqtt_port);
  mqtt_user = readEEPROM(MQTT_USER_ADDR, 32);
  mqtt_password = readEEPROM(MQTT_PASSWORD_ADDR, 32);
  mqtt_topic_power = readEEPROM(MQTT_TOPIC_POWER_ADDR, 64);
  mqtt_topic_boost = readEEPROM(MQTT_TOPIC_BOOST_ADDR, 64);
  mqtt_topic_heat = readEEPROM(MQTT_TOPIC_HEAT_ADDR, 64);
  mqtt_topic_status = readEEPROM(MQTT_TOPIC_STATUS_ADDR, 64);
  EEPROM.get(MQTT_ATTEMPTS_ADDR,mqtt_attempts);
  mqtt_reconnection = EEPROM.read(MQTT_RECONNECTION_ADDR);
  EEPROM.get(MQTT_TIME_PUBLICATION_ADDR,mqtt_time_publication);
  EEPROM.end();

  Serial.println();
  Serial.println("mqtt_server:           " + mqtt_server);
  Serial.println("mqtt_port:             " + String(mqtt_port));
  Serial.println("mqtt_user:             " + mqtt_user);
  Serial.println("mqtt_password:         " + mqtt_password);
  Serial.println("mqtt_topic_power:      " + mqtt_topic_power);
  Serial.println("mqtt_topic_boost:      " + mqtt_topic_boost);
  Serial.println("mqtt_topic_heat:       " + mqtt_topic_heat);
  Serial.println("mqtt_attempts:         " + String(mqtt_attempts));
  Serial.println("mqtt_time_publication: " + String(mqtt_time_publication));
  Serial.println("mqtt_reconnection:     " + String(mqtt_reconnection));
  Serial.println();
  }

}
// Функция для обработки входящих MQTT сообщений
void mqttCallback(char* topic, byte* payload, unsigned int length) {
  #ifdef ENABLE_MQTT
  String message;
  for (int i = 0; i < length; i++) {
    message += (char)payload[i];
  }

  // Управление только при активном подключении
  if (mqttClient.connected()) {
    if (String(topic) == mqtt_topic_power) {
        setPower(message.toInt());      // Установка мощности
        mqttClient.publish(mqtt_topic_status.c_str(), ("Power set to: " + String(powerSetpoint)).c_str());
      }
    } else if (String(topic) == mqtt_topic_boost) {
      // Включение/выключение режима разгона
      if (message == "1") {
        boost(ON);
        mqttClient.publish(mqtt_topic_status.c_str(), "Boost mode enabled");
      } else if (message == "0") {
        boost(OFF);
        mqttClient.publish(mqtt_topic_status.c_str(), "Boost mode disabled");
      }
   } else if (String(topic) == mqtt_topic_heat) {
    // Включение/выключение нагрева
    if (message == "1") {
      heat(ON);
      mqttClient.publish(mqtt_topic_status.c_str(), "Heat enabled");
    } else if (message == "0") {
      heat(OFF);
      mqttClient.publish(mqtt_topic_status.c_str(), "Heat disabled");
    }
  }
#endif 
}

// Функция для подключения к MQTT-брокеру с 1 попытками
void mqttConnect() {
  #ifdef ENABLE_MQTT
  int attempts = 0;
  while (!mqttClient.connected() && attempts < mqtt_attempts ) { // Попытки 
    Serial.print("Attempting MQTT connection...");
    if (mqttClient.connect("ESP12E_Stabilizer", mqtt_user.c_str(), mqtt_password.c_str())) {
      Serial.println("connected");
      mqttClient.subscribe(mqtt_topic_power.c_str());
      mqttClient.subscribe(mqtt_topic_boost.c_str());
      mqttClient.subscribe(mqtt_topic_heat.c_str());
    } else {
      Serial.print("failed, rc=");
      Serial.print(mqttClient.state());
      Serial.println(" try again in 1 seconds");
      delay(5000);
      attempts++;
    }
  }
  if (attempts >= mqtt_attempts) {
    Serial.println("Failed to connect to MQTT broker after " + String(mqtt_attempts) + " attempts.");
  }
  #endif 
}

// Инициализация MQTT
void setupMQTT() {
  #ifdef ENABLE_MQTT
  readMQTTSettings(); // Чтение параметров MQTT из EEPROM
  mqttClient.setServer(mqtt_server.c_str(), mqtt_port);
  mqttClient.setCallback(mqttCallback);
  mqttConnect();
  #endif 
}

// Обновление MQTT в основном цикле
void loopMQTT() {
  #ifdef ENABLE_MQTT
    static unsigned long timeout = millis(); //раз в минуту проверяем соединение с mqtt сервером если включена настройка
  if (millis() - timeout >= 60000) { 
  if (mqtt_reconnection && !mqttClient.connected()) {
      if (mqttClient.connect("ESP12E_Stabilizer", mqtt_user.c_str(), mqtt_password.c_str())) {
      mqttClient.subscribe(mqtt_topic_power.c_str());
      mqttClient.subscribe(mqtt_topic_boost.c_str());
      mqttClient.subscribe(mqtt_topic_heat.c_str());
    }
  }//*/
    timeout = millis();                    //перезапуск секундного таймера
  }    
  mqttClient.loop();
  // Публикация текущего статуса только при активном подключении
  if (mqttClient.connected()) {
    static unsigned long lastStatusUpdate = 0;
    if (millis() - lastStatusUpdate > 1000 ) { // mqtt_time_publication
      String status = "TP= " + String(powerSetpoint) + " W, P= " + String(power) + " W, U= " + String(voltage,1) + " V, I= " + String(current,2) + " A, S= " + String(energy, 3) + " kWh";
      mqttClient.publish(mqtt_topic_status.c_str(), status.c_str());
      lastStatusUpdate = millis();
    }
  }
  #endif 
}