#include <Arduino.h>
#include <U8g2lib.h>

#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif

int progress, total;
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* rest= */ U8X8_PIN_NONE, /* clock= */ 22, /* data= */ 21);

void setup(void) {
  Serial.begin(115200);
  u8g2.begin();
  progress = 88, total = 100;
}

void loop(void) {
  //u8g2.clearBuffer();					// clear the internal memory
  //u8g2.setFont(u8g2_font_ncenB08_tr);	// choose a suitable font
  //u8g2.drawStr(0, 10, "Hello World!");	// write something to the internal memory
  // u8g2.sendBuffer();					// transfer internal memory to the display
  //delay(1000);
  if (progress)
    progress--;
  else progress = 100;
  Serial.printf("Progress: %u%%\r", progress / (total / 100));
  /*u8g2.firstPage();
    do {
    u8g2.drawRFrame(0, 0, 88, 48, 3);
    u8g2.setFont(u8g2_font_6x10_tr);
    u8g2.setFontPosTop();
    u8g2.drawStr(0, 0, "SW Updating!");
    } while (u8g2.nextPage());
    delay(2000);*/
  u8g2.firstPage();
  do {
    u8g2.drawRFrame(0, 0, 88, 48, 3);
    u8g2.setFont(u8g2_font_6x10_tr);
    u8g2.setFontPosTop();
    u8g2.drawStr(0, 0, "SW Updating!");
    u8g2.drawFrame(4, 20, 80, 8);
    u8g2.drawBox(5, 21, map(progress / (total / 100), 0, 100, 0, 78), 6);
    u8g2.setCursor(0, 36);
    u8g2.printf("%d%%", progress / (total / 100));
    //u8g2.print(F("%"));
  } while (u8g2.nextPage());
  delay(100);
  /*
    u8g2.firstPage();
    do {
    u8g2.drawRFrame(0, 0, 88, 48, 3);
    u8g2.setFont(u8g2_font_6x10_tr);
    u8g2.setFontPosTop();
    u8g2.drawStr(0, 36, "Restarting!");
    } while (u8g2.nextPage());
    delay(2000);*/
}