#include <WiFi.h>
#include "wifi-credentials.h"
#include "connection-wifi.h"
#include "gps.h"
#include "dht.h"
#include "senddata.h"
#include "functions.h"

uint64_t sleepInterval = 60 * 5; // Sleep for 5 minutes

int TIME_TO_SLEEP_IN_SECONDS = 5; // 
unsigned long uS_TO_S_FACTOR = 1000000;

void gatherDataAndSend() {
    char* temp = readTemperature();
    Serial.print("Temperature: ");Serial.println(temp);

    char* latlng = readGPS();
    Serial.print("GPS: ");Serial.println(latlng);

    char* data = createQueryString(temp, latlng);
    Serial.print("data: "); Serial.println(data);

    sendData(data);

    free(temp);
    free(latlng);
    free(data);
}

void setup() {
  Serial.begin(115200);
  Serial.println("### ### ### ### ### ### ### ### ### ### ###");
  GPS_SERIAL.begin(115200);
  dht.setup(DHT_PIN, DHTesp::DHT22);

  gatherDataAndSend();
  
  esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP_IN_SECONDS * uS_TO_S_FACTOR * 60);
  Serial.flush();
  esp_deep_sleep_start();
}

void loop() {
  Serial.println("### ### ### this is loop - should not have been called.");

  // Gather data and send to server:
  //gatherDataAndSend();

  // Enter deep sleep mode:
  //esp_deep_sleep(sleepInterval * 1000000); // Convert seconds to microseconds
}