#include <ESP8266WiFi.h>
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#include <OneWire.h>
#include <DallasTemperature.h>

// ---- Pin Definitions ----
#define ONE_WIRE_BUS 14
#define BUZZER_PIN 12

// ---- Sensor Objects ----
PulseOximeter pox;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature tempSensor(&oneWire);

// ---- Global Variables ----
float bpm = 0, spo2 = 0, temperature = 0;
bool readTempPhase = false;
unsigned long lastCycle = 0;
bool sensorInitialized = false;

// ---- Setup ----
void setup() {
  Serial.begin(115200);
  pinMode(BUZZER_PIN, OUTPUT);
  noTone(BUZZER_PIN);
  tempSensor.begin();
  Wire.begin();

  initMAX30100();  // try once initially
}

// ---- MAX30100 Init with Retry ----
void initMAX30100() {
  sensorInitialized = pox.begin();
  if (sensorInitialized) {
    pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);
    pox.setOnBeatDetectedCallback([]() {
      Serial.println("Beat detected!");
    });
    Serial.println("MAX30100 initialized");
  } else {
    Serial.println("MAX30100 init FAILED");
  }
}

// ---- Loop ----
void loop() {
  pox.update();
  unsigned long now = millis();

  if (!readTempPhase && now - lastCycle >= 2000) {
    // ---- Phase 1: HR and SpO2 ----
    if (!sensorInitialized) {
      initMAX30100();  // Re-init if disconnected
    }

    bpm = pox.getHeartRate();
    spo2 = pox.getSpO2();

    if (spo2 < 90 || bpm < 40 || bpm > 180) {
      tone(BUZZER_PIN, 1000);
    } else {
      noTone(BUZZER_PIN);
    }

    readTempPhase = true;
    lastCycle = now;
  }

  else if (readTempPhase && now - lastCycle >= 1000) {
    // ---- Phase 2: Temperature ----
    tempSensor.requestTemperatures();
    temperature = tempSensor.getTempCByIndex(0);

    // ---- Print Final JSON ----
    String jsonData = "{\"Heart_beat_rate\":" + String(bpm, 1) +
                      ",\"Sp02_level\":" + String(spo2, 1) +
                      ",\"Temperature\":" + String(temperature, 1) + "}";

    Serial.println(jsonData);
    readTempPhase = false;
    lastCycle = now;
  }
}
