#include <Adafruit_GFX.h>
#include <Adafruit_SPITFT.h>
#include <Adafruit_SPITFT_Macros.h>
#include <gfxfont.h>
#include <Adafruit_SSD1306.h>
#include <splash.h>
#include <SPI.h>
#include <SD.h>
#include <Wire.h>

#include <MFRC522.h>
#include <RTClib.h>

#define RST_PIN         9          
#define SS_PIN          10
#define BTN_READ        2
#define BTN_IMPRINT     3
#define BTN_MENU        4
#define BTN_UP          5
#define BTN_DOWN        6

#define SCREEN_WIDTH    64          
#define SCREEN_HEIGHT   48          
#define OLED_RESET      -1          
#define LOGO_HEIGHT     16          
#define LOGO_WIDTH      16          

RTC_DS3231 rtc;

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
MFRC522 mfrc522(SS_PIN, RST_PIN);
File dataFile;

boolean read = false;
boolean imprint = false;
boolean menuActive = false;
boolean up = false;
boolean down = false;

void setup() {
  Serial.begin(9600);
  SPI.begin();      
  mfrc522.PCD_Init(); 

  pinMode(BTN_READ, INPUT_PULLUP);
  pinMode(BTN_IMPRINT, INPUT_PULLUP);
  pinMode(BTN_MENU, INPUT_PULLUP);
  pinMode(BTN_UP, INPUT_PULLUP);
  pinMode(BTN_DOWN, INPUT_PULLUP);

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

  if (!SD.begin(SS_PIN)) {
    Serial.println("SD Card failed, or not present");
    while (1);
  }

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0,0);
  display.println("Initializing...");
  display.display();
  delay(1000);
  display.clearDisplay();
}

void loop() {

  DateTime now = rtc.now();
  int batteryVoltage = analogRead(A0);
  float batteryPercent = map(batteryVoltage, 0, 1023, 0, 100);

  display.clearDisplay();
  display.setCursor(0,0);
  display.print(now.day());
  display.print('/');
  display.print(now.month());
  display.setCursor(26,0);
  display.print(now.hour(), DEC);
  display.print(':');
  if (now.minute() < 10) {
    display.print('0');
  }
  display.print(now.minute(), DEC);
  display.setCursor(51,0);
  display.print(batteryPercent);
  display.print("%");

  if (menuActive) {
    display.setCursor(0,9);
    display.println("Menu");
    display.drawLine(0,10,63,10,WHITE);
    display.setCursor(0,20);
    display.println("1. Diagnostics");
    display.setCursor(0,30);
    display.println("2. Option 2");
    display.setCursor(0,40);
    display.println("3. Option 3");
    if (up) {
      display.drawTriangle(57,16,57,0,63,8,WHITE);
    } else if (down) {
      display.drawTriangle(57,32,57,48,63,40,WHITE);
    }
  } else (read);
}