#include <SPI.h>
#include <Ethernet.h>
#include <TimeLib.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0x05 };
char timeServer[] = "time.nist.gov";
EthernetUDP Udp;
unsigned int localPort = 8888;

const int NTP_PACKET_SIZE = 48;
byte packetBuffer[NTP_PACKET_SIZE]; // Definerer packetBuffer som en global variabel

struct TimeSlot {
  const char* day;
  const char* startTime;
  const char* endTime;
  const char* type;
  const char* subject;
};

TimeSlot schedule[] = {
  {"Mandag", "08:00", "08:45", "Time", "Matematikk"},
  {"Mandag", "08:45", "09:00", "Friminutt", ""},
  {"Mandag", "09:00", "09:45", "Time", "Norsk"},
  {"Mandag", "09:45", "10:00", "Friminutt", ""},
  // Legg til flere timeplaner her
  {"Fredag", "13:00", "13:45", "Time", "Engelsk"},
  {"Fredag", "13:45", "14:00", "Friminutt", ""}
};

const int scheduleSize = sizeof(schedule) / sizeof(schedule[0]);

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac);
  Udp.begin(localPort);
  setSyncProvider(getNtpTime);
  Serial.println("TEST ");
}

void loop() {
  if (timeStatus() != timeNotSet) {
    for (int i = 0; i < scheduleSize; i++) {
      if (isCurrentTimeSlot(schedule[i])) {
        int secondsLeft = calculateSecondsLeft(schedule[i].endTime);
        Serial.print("Type: ");
        Serial.print(schedule[i].type);
        Serial.print(", Fag: ");
        Serial.print(schedule[i].subject);
        Serial.print(", Sekunder igjen: ");
        Serial.println(secondsLeft);
      }
    }
  }
  delay(1000);
}

bool isCurrentTimeSlot(TimeSlot slot) {
  // Sjekk om nåværende dag og tid er innenfor timeplanens tidsrom
  // Implementer logikken her
  return false; // Midlertidig
}

int calculateSecondsLeft(const char* endTime) {
  // Beregn antall sekunder igjen til sluttidspunktet
  // Implementer logikken her
  return 0; // Midlertidig
}

time_t getNtpTime() {
  sendNTPpacket(timeServer);
  delay(1000);
  if (Udp.parsePacket()) {
    Udp.read(packetBuffer, NTP_PACKET_SIZE);
    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    const unsigned long seventyYears = 2208988800UL;
    unsigned long epoch = secsSince1900 - seventyYears;
    return epoch;
  }
  return 0;
}

void sendNTPpacket(const char *address) {
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  packetBuffer[0] = 0b11100011;
  packetBuffer[1] = 0;
  packetBuffer[2] = 6;
  packetBuffer[3] = 0xEC;
  packetBuffer[12] = 49;
  packetBuffer[13] = 0x4E;
  packetBuffer[14] = 49;
  packetBuffer[15] = 52;
  Udp.beginPacket(address, 123);
  Udp.write(packetBuffer, NTP_PACKET_SIZE);
  Udp.endPacket();
}