#include "clock.h"

bool RTC_present = false;
bool provider_Set = false;
// // Central European Time (Frankfurt, Paris)
TimeChangeRule CEST = {"CEST", Last, Sun, Mar, 2, 120};     // Central European Summer Time
TimeChangeRule CET = {"CET ", Last, Sun, Oct, 3, 60};       // Central European Standard Time
Timezone myTZ(CEST, CET);

TimeChangeRule *tcr;

bool timeIsSet()
{
  return RTC_present;
}

void printDateTime(time_t t, const char *tz)
{
    char buf[32];
    char m[4];    // temporary storage for month string (DateStrings.cpp uses shared buffer)
    strcpy(m, monthShortStr(month(t)));
    sprintf(buf, "%.2d:%.2d:%.2d %s %.2d %s %d %s",
        hour(t), minute(t), second(t), dayShortStr(weekday(t)), day(t), m, year(t), tz);
    Serial.println(buf);
}

time_t getLocalTime()
{
  if(!getWifiStatus()) return 0;
  time_t utc;
  time(&utc);
  time_t local = myTZ.toLocal(utc, &tcr);
  printDateTime(local,tcr -> abbrev);
  printDateTime(utc,"UTC");

  return local;
}

void initClock()
{
  getLocalTime();
}


void loopClock()
{
 if(getWifiStatus())
  {
    if(getWifiStatus() & !provider_Set)
    {
      setSyncProvider(getLocalTime);
      setSyncInterval(10);
      provider_Set = true;
      log_i("timesync provider set");
    }

    RTC_present = timeStatus ? timeSet: true, false;
  }
  else
  {
    RTC_present = false;
  }
}

String getTimeNow()
{ 
  return PreZero(hour())+PreZero(minute())+PreZero(second());
}

String updateDateString()
{
  return PreZero(day())+PreZero(month())+PreZero(year()%1000);
}
