#include <Arduino.h>
#include <WiFi.h>
#include <mqtt_client.h>

#define POTENTIOMETER 35
#define BUTTON 23

const float BETA = 3950;
bool buttonState = false;
int previousButtonValue = 0;
int temperature = 0;

const char ssid[] = "ESGI";
const char password[] = "Reseau-GES";
const char mqtt_uri[] = "mqtt://mosquitto.nospy.fr:1883";
const char main_topic[] = "test";
void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data);
esp_mqtt_client *client = nullptr;

const char hydrogen_topic[] = "hydrogen";
const char temperature_topic[] = "temperature";

void setPins();
void connectWifi();
void connectMQTT();
float readPotentiometer();
char* convertIntToChar(int number);

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

  setPins();
  
  connectWifi();
  connectMQTT();
}

void loop() 
{
  int potentiometerValue = int(readPotentiometer());
  int buttonValue = digitalRead(BUTTON);
  
  Serial.println(potentiometerValue);
  Serial.println(buttonState);
  
  if (potentiometerValue != temperature) 
  {
    temperature = potentiometerValue;
    
    esp_mqtt_client_publish(client, temperature_topic, convertIntToChar(temperature), 0, 0, 0);
  }
  
  if (previousButtonValue == 1 && buttonValue == 0) 
  {
    buttonState = !buttonState;
    
    esp_mqtt_client_publish(client, hydrogen_topic, buttonState == 0 ? "0" : "1", 0, 0, 0);
  }
  
  previousButtonValue = buttonValue;
  
  delay(100);
}

void setPins() {
  pinMode(POTENTIOMETER, INPUT);
  pinMode(BUTTON, INPUT_PULLUP);
}

void connectWifi() {
    WiFiClass::mode(WIFI_STA);
    WiFi.begin(ssid, password);

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

    while (WiFiClass::status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void connectMQTT() {
    Serial.print("Attempting to connect to the MQTT broker: ");
    Serial.println(mqtt_uri);
    esp_mqtt_client_config_t mqtt_cfg = {
            .uri = mqtt_uri,
            .client_id = "ESP32",
    };
    client = esp_mqtt_client_init(&mqtt_cfg);
    esp_err_t ret = esp_mqtt_client_start(client);
    if (ret != ESP_OK) {
        Serial.printf("Error starting MQTT client: %s\n", esp_err_to_name(ret));
    } else {
        Serial.printf("MQTT client connected successfully.\n");
    }
}

float readPotentiometer() {
  return analogRead(POTENTIOMETER) * 120 / 4095;
}

char* convertIntToChar(int number){
    char valueString[10];
    
    sprintf(valueString, "%d", temperature);

    return valueString;
}