#include <ArduinoJson.h>

#include "LumiPalette.h"
#include "SdFat.h"

#define NUM_PALETTES 10
#define MAX_TAGS 4

#define SPI_SPEED SD_SCK_MHZ(4)
#define CS_PIN 10

LumiPalette pal[NUM_PALETTES] = {0};
int pIndex[NUM_PALETTES] = {0};

DynamicJsonDocument doc(200);

SdFat sd;

void setup() {
  Serial.begin(115200);

  if (!sd.begin(CS_PIN, SPI_SPEED)) {
    if (sd.card()->errorCode()) {
      Serial.println("SD initialization failed.");
    } else if (sd.vol()->fatType() == 0) {
      Serial.println("Can't find a valid FAT16/FAT32 partition.");
    } else {
      Serial.println("Can't determine error type");
    }
    return;
  }

  Serial.println("Files on card:");
  Serial.println("   Size    Name");

  int docCap = doc.capacity();
  Serial.println(docCap);

  sd.ls(LS_R | LS_SIZE);

  File file = sd.open("palettes.json");
  DeserializationError err = deserializeJson(doc,file);
  file.close();  // We don't need the file anymore

if (err) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(err.c_str());
}
  // JsonObject obj = doc.as<JsonObject>();

  serializeJsonPretty(doc, Serial);

  // for( int i = 0; i <= NUM_PALETTES; i++ ) {
  //   int index = obj["palettes"][i]["index"];
  //   const char* label = obj["palettes"][i]["label"];
  //   Serial.println(label);
  // }


  // int numPalettesFound = getPalettesByTag(pIndex,BRIGHT);

  // for( int i = 0; i <= numPalettesFound; i++ ) {
  //   Serial.println(pIndex[i]);
  // }
}

void loop() {
  // put your main code here, to run repeatedly:
  // delay(50); // this speeds up the simulation
}

// Returns int, number of palettes matching tag
int getPalettesByTag( int * pIndexes, PaletteTag tag) {
    int indexIndex = 0;

    for( int i = 0; i < NUM_PALETTES; i++ ) {
      for( int j = 0; j < MAX_TAGS; j++)
      if( pal[i].tags[j] == tag) {
        pIndexes[indexIndex] = pal[i].index;
        indexIndex++;
      }
    }
    return indexIndex - 1;
}

void parsePaletteJson() {

}
uno:A5.2
uno:A4.2
uno:AREF
uno:GND.1
uno:13
uno:12
uno:11
uno:10
uno:9
uno:8
uno:7
uno:6
uno:5
uno:4
uno:3
uno:2
uno:1
uno:0
uno:IOREF
uno:RESET
uno:3.3V
uno:5V
uno:GND.2
uno:GND.3
uno:VIN
uno:A0
uno:A1
uno:A2
uno:A3
uno:A4
uno:A5
sd1:CD
sd1:DO
sd1:GND
sd1:SCK
sd1:VCC
sd1:DI
sd1:CS