#include <neoPixel.h>
#include "SDTools.h"
#include "bmpImage.h"
#include "filePath.h"
#include <resizeBuff.h>

#define SD_CS   4     // SD chip select pin number. Change to suit your setup.

neoPixel    display(32*32,2);
filePath    wd;

void setup() {

	Serial.begin(9600);
	SD.begin(SD_CS); 
  wd.setPath("/System/icons/standard/");  
  display.begin();
}


void setPixelColor(int x,int y,colorObj* color) {
  display.setPixelColor(32*y+x,color);
}


void displayBmp(const char* bmpPath) {

  bmpImage  theImage(bmpPath);
  RGBpack   thePixel;
  colorObj  aColor;

  theImage.openDocFile(FILE_READ);
  for (int y=0;y<32;y++) {
    for (int x=0;x<32;x++) {
      thePixel = theImage.getRawPixel(x,y);
      aColor.setColor(&thePixel);
      setPixelColor(x,y,&aColor);
    }
  }
  theImage.closeDocFile();
  display.show();
}


bool checkFile(pathItem*	item) {

  if (item->name[0]=='.') return false;
  if (!strstr(item->name,"32.BMP")) return false; 
  return true;
}


void listDirectory(void) {

  pathItem*		trace;
  int         numBytes;
  char*       path;
  
  path = NULL;                                                          //
  if (wd.getPathType()==fileType) {                             // If this is pointing to a file..? 
    Serial.println("Sorry, this is a file, not a directory.");  // Just wrong, we can't list a file.
    return;                                                     // Just walk away..
  } else {                                                      // Else, not a file. Good!
    numBytes = wd.numPathBytes();
    numBytes = numBytes + 14;
    resizeBuff(numBytes,&path);
    wd.refreshChildList();                                      // Make sure we have an up to date child list..
    if (wd.numChildItems()==0) {                                // Wait, no children to list?
      Serial.println("This directory is empty.");               // Tell the user.
      return;                                                   // And walk away.
    } else {                                                    // Else, we DO have kids to list.
      trace = wd.childList;																	    // Grab a pointer to the first child.
      while(trace) {																						// While we have a non-NULL pointer..
        if (checkFile(trace)) {																	// Pass this child through the crucible of the user's filter function.
          strcpy(path,wd.getPath());
          strcat(path,trace->getName());
          Serial.println(path);
          displayBmp(path);
          delay(2000);
        }                                                       //
        trace = (pathItem*)trace->dllNext;											// Jump to the next item on the list.
      }
    }
  }
  resizeBuff(0,&path);
}


// Your loop where it parses out all your typings.
void loop(void) {
	listDirectory();
  delay(2000);
}