#include <logger.h>
#include "config.hpp"
#include "eink.hpp"
#include "io.hpp"

logging::Logger logger;
Eink eink;
IO io;

RTC_DATA_ATTR int bootCount = 0;
RTC_DATA_ATTR int updateCount = 0;
RTC_DATA_ATTR float last_temp = 20;
RTC_DATA_ATTR int last_battery = 0;
bool update = false;


void setup()
{
  Serial.begin(115200);
  logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "MAIN", "Boot number: %i", bootCount);
  update = false;
#ifndef DEBUG
  logger.setDebugLevel(logging::LoggerLevel::LOGGER_LEVEL_INFO);
#endif
  io.setup_io();
  io.set_low_power();
  
  uint8_t battery = io.read_battery();
  if (abs(battery - last_battery) >= 2)
  {
    last_battery = battery;
    update = true;
  }
  logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "MAIN", "Battery: %i", battery);
  
  float temp = io.read_temp();
  
  logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "MAIN", "TEMP: %f", temp);
  if (abs(temp - last_temp) >= 0.5 && temp > -120)
  {
    last_temp = temp;
    update = true;
  }

  float internal_temp = io.read_internal_temp();
  eink.setup_eink();

  ++bootCount;
  if (update)
  {
    ++updateCount;
    eink.drawBattery(186, 14, battery);        // eink width 250 - drawbattery width
    eink.drawSignalBars(180 - 24 - 4, 12, 84); //  drawbattery width - drawsignal
    logger.log(logging::LoggerLevel::LOGGER_LEVEL_INFO, "MAIN", "TEMP: %f", temp);
    eink.show_temp(temp);
    eink.show_internal_temp(180 - 24 - 4 - 100, 12, internal_temp);
    eink.show_count(180 - 24 - 4 - 100 - 60, 12, (float)bootCount, "c: ");
    eink.show_count(180 - 24 - 4 - 100 - 60 - 50, 12, (float)bootCount, "u: ");
    eink.display(true);
  }
  io.set_deep_sleep();
}

void loop()
{
}
