#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() {

}