#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include "SSID_Pass.h"

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET    -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

const char* ssid = WIFI_SSID;
const char* password = WIFI_PASSWORD;
const int blink_count = sizeof(blink_list) / sizeof(blink_list[0]);

void tampilkan_ekspresi(int index, ) {
  display.clearDisplay();
  display.drawBitmap(32, 0, ekspresi_list[index], 64, 64, WHITE);
  display.display();
}

WiFiUDP udp;
NTPClient timeClient(udp, "pool.ntp.org", 25200, 60000);

#define BATTERY_PIN 6  

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

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }

  display.clearDisplay();

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");

  timeClient.begin();
}

void loop() {
  timeClient.update();
  String formattedTime = timeClient.getFormattedTime();
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);


  int rawADC = analogRead(BATTERY_PIN);
  float voltage = (rawADC / 4095.0) * 3.3 * 2; 
  float percentage;
  if (voltage >= 4.2) {
    percentage = 100;
  } else if (voltage > 3.9) {
    percentage = 75 + (voltage - 3.9) * 100 / (4.2 - 3.9);
  } else if (voltage > 3.7) {
    percentage = 50 + (voltage - 3.7) * 25 / (3.9 - 3.7);
  } else if (voltage > 3.5) {
    percentage = 25 + (voltage - 3.5) * 25 / (3.7 - 3.5);
  } else {
    percentage = (voltage - 3.0) * 25 / (3.5 - 3.0);
  }


  int x_offset = ((SCREEN_WIDTH - 64) / 2)-1;  
  int y_offset = ((SCREEN_HEIGHT - 64) / 2);
  display.drawBitmap(x_offset, y_offset, happy, 64, 64, WHITE);
  display.display();
  

  // int16_t x1, y1;
  // uint16_t w, h;
  // display.getTextBounds("Time:", 0, 0, &x1, &y1, &w, &h);
  // int centerXTime = (SCREEN_WIDTH - w) / 2;

  // display.setCursor(centerXTime, 10);
  // display.print("Time:");


  // display.setTextSize(2);
  // display.getTextBounds(formattedTime.c_str(), 0, 0, &x1, &y1, &w, &h);
  // int centerXTimeValue = (SCREEN_WIDTH - w) / 2;

  // display.setCursor(centerXTimeValue, 30);
  // display.println(formattedTime);


  // display.setTextSize(1);
  // display.setCursor(10, 50);
  // display.print("Bat : ");
  // display.print(percentage, 2);
  // display.display();
  // delay(1000);
}