#include "TFTLCD.h"
#include "TouchScreen.h"
#include <SD.h>

#define YP A3  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 9   // can be a digital pin
#define XP 8   // can be a digital pin

#define TS_MINX 150
#define TS_MINY 120
#define TS_MAXX 920
#define TS_MAXY 940

// For better pressure precision, we need to know the resistance
// between X+ and X- Use any multimeter to read it
// For the one we're using, its 300 ohms across the X plate
TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// The control pins can connect to any pins but we'll use the 
// analog lines since that means we can double up the pins
// with the touch screen (see the TFT paint example)
#define LCD_CS A3    // Chip Select goes to Analog 3
#define LCD_CD A2    // Command/Data goes to Analog 2
#define LCD_WR A1    // LCD Write goes to Analog 1
#define LCD_RD A0    // LCD Read goes to Analog 0
/* For the 8 data pins:
Duemilanove/Diecimila/UNO/etc ('168 and '328 chips) microcontoller:
D0 connects to digital 8
D1 connects to digital 9
D2 connects to digital 2
D3 connects to digital 3
D4 connects to digital 4
D5 connects to digital 5
D6 connects to digital 6
D7 connects to digital 7

For Mega's use pins 22 thru 29 (on the double header at the end)
*/

// For Arduino Uno/Duemilanove, etc
//  connect the SD card with DI going to pin 11, DO going to pin 12 and SCK going to pin 13 (standard)
//  Then pin 10 goes to CS (or whatever you have set up)
#define SD_CS 10     // Set the chip select line to whatever you use (10 doesnt conflict with the library)

// In the SD card, place 24 bit color BMP files (be sure they are 24-bit!)
// There are examples in the sketch folder

// optional
#define LCD_RESET A4

// Color definitions
#define	BLACK               0 //0x0000
#define	BLUE               31 //0x001F
#define	GREEN            2016 //0x07E0
#define CYAN             2047 //0x07FF
#define	RED             63488 //0xF800
#define MAGENTA         63519 //0xF81F
#define YELLOW          65504 //0xFFE0 
#define WHITE           65535 //0xFFFF

// our TFT wiring
TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);

// information we extract about the bitmap file
int penRadius, bmpWidth, bmpHeight, oldC, newC;
uint8_t bmpDepth, bmpImageoffset;


int pageWidth = 320;
int pageHeight = 240;
int numBoxesRow = 8;
int numBoxesCol = 8;
int boxHeight = 40;
int boxWidth = pageHeight/numBoxesCol;

// the file itself
File bmpFile;
char* fName = "001.txt";

void setup()
{
  Serial.begin(115200);
  Serial.println("Paint with a spashscreen\n\nBy:\ncbwp.net!\n\n");
 
  tft.reset();
  
  // find the TFT display
  uint16_t identifier = tft.readRegister(0x0);
  if (identifier == 0x9325) {
    Serial.println("Found ILI9325");
  } else if (identifier == 0x9328) {
    Serial.println("Found ILI9328");
  } else {
    Serial.print("Unknown driver chip ");
    Serial.println(identifier, HEX);
    while (1);
  }  
 
  tft.initDisplay();
  Serial.print("Initializing SD card...");
  pinMode(10, OUTPUT);

  if (!SD.begin(10)) {
    Serial.println("SD Init failed!");
  } else {
    Serial.println("SD OK!");
  }
  /*
    bmpFile = SD.open("ziva.bmp");

    if (! bmpFile) {
      Serial.println("didnt find image");
    } else if (! bmpReadHeader(bmpFile)) { 
       Serial.println("bad bmp");
    } else {
      Serial.print("image size "); 
      Serial.print(bmpWidth, DEC);
      Serial.print(", ");
      Serial.println(bmpHeight, DEC);
 
      tft.fillScreen(BLACK);
      bmpdraw(bmpFile, 0, 0);
      bmpFile.close();
      delay(2000);
    }
  }
  //int cRGB = tft.Color565(255, 165, 00);//orange rgb(FF, A5, 00)
  */
  
  tft.fillScreen(BLACK);
  tft.drawPixel(0,0,3000);
  tft.drawPixel(1,0,6000);
  tft.drawPixel(2,0,9000);
  tft.drawPixel(3,0,12000);
  tft.drawPixel(4,0,15000);
  tft.drawPixel(5,0,18000);
  tft.drawPixel(6,0,21000);
  tft.drawPixel(7,0,24000);
  tft.drawPixel(8,0,27000);
  tft.drawPixel(9,0,30000);
  
  Serial.println("Got the pixels");
  Serial.println("Saving file");
  SD.remove(fName);
  bmpFile = SD.open(fName, FILE_WRITE);
  if (bmpFile) {
    for(int x = 0; x < 10; x++){
      int c = getPixel(x, 0);
      Serial.println(c);
      bmpFile.println(c);
    }
    bmpFile.close();
    Serial.println("Done saving.");
  }
  
  box(40, 100, 140, 35, 2047, 2016, 2078, 2, 3, "Your momma");
  // width = num char * 12 + 20
  //where 0,0 = top left and width = 240
//  drawBox();loadBox();saveBox();paletteBox();
 
//  tft.drawRect(0, 0, boxWidth, boxHeight, WHITE);
  newC = RED;

  pinMode(13, OUTPUT);
  pinMode(19, INPUT); // get penRadius from analog input

}

void saveBmp(){
  SD.remove(fName);
  bmpFile = SD.open(fName, FILE_WRITE);

  // if the file opened okay, write to it:
  if (bmpFile) {
    Serial.print("Saving ");Serial.print(fName);Serial.print("...");
    int cSave;
    for(int y = 0; y < 320; y++){
      for(int x = 0; x < 240; x++){
        cSave = getPixel(x, y);
        bmpFile.println(cSave);
        Serial.print(x);
        Serial.print(",");
        Serial.print(y);
        Serial.print(",");
        Serial.print(cSave);
        Serial.print(":");
      }
      Serial.print("\n");
    }
    // close the file:
    bmpFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error writing to file");
  }
}  

void loadBmp(){
  tft.fillScreen(BLACK);
  // open the file for reading:
  bmpFile = SD.open(fName);
  if (bmpFile) {
    Serial.print("Reading ");Serial.print(fName);Serial.print("...");
    
    // read from the file until there's nothing else in it:
    while (bmpFile.available()) {
      for(int y = 0; y < 320; y++){
        for(int x = 0; x < 240; x++){
          int cP = cValue();
          tft.drawPixel(x, y, cP);
        Serial.print(x);
        Serial.print(",");
        Serial.print(y);
        Serial.print(",");
        Serial.print(cP);
        Serial.print(":");
      }
      Serial.print("\n");
      }
    }
    // close the file:
    bmpFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error reading from file");
  }
}

int lCfunc(){
  int lC;
  lC = 65536 + bmpFile.read();
  if(lC == 65536){ lC = 0; }
  return lC;
}

int cValue(){
  int junk, cP, lC;
  lC = lCfunc();
  cP  = (lC - 48) * 10000;
  lC = lCfunc();
  cP += (lC - 48) * 1000;
  lC = lCfunc();
  cP += (lC - 48) * 100;
  lC = lCfunc();
  cP += (lC - 48) * 10;
  lC = lCfunc();
  cP += (lC - 48) * 1;
  junk = bmpFile.read();
  junk = bmpFile.read();
/*
// Color definitions
#define	RED             63488 //0xF800
#define YELLOW          65504 //0xFFE0 
#define	GREEN            2016 //0x07E0
#define CYAN             2047 //0x07FF
#define	BLUE               31 //0x001F
#define MAGENTA         63519 //0xF81F
#define	BLACK               0 //0x0000
#define WHITE           65535 //0xFFFF
*/
  switch(cP){
    case -2048:
      cP = RED;
    break;
    case -32:
      cP = YELLOW;
    break;
    case 2016:
      cP = GREEN;
    break;
    case 2047:
      cP = CYAN;
    break;
    case 31:
      cP = BLUE;
    break;
    case -2017:
      cP = MAGENTA;
    break;
    case 0:
      cP = BLACK;
    break;
    case -1:
      cP = WHITE;
    break;
  }
  return cP;
}

int getPixel(int x, int y){
  tft.writeRegister(0x0020, x); // GRAM Address Set (Horizontal Address) (R20h)
  tft.writeRegister(0x0021, y); // GRAM Address Set (Horizontal Address) (R20h)
  int junk = tft.readRegister(0x0022);
  int c = tft.readRegister(0x0022);
  return c;
}

#define MINPRESSURE 10
#define MAXPRESSURE 1000
boolean paused = false;

void loop()
{}void nullFunction() // leave uncommented to skip loop
{
  digitalWrite(13, HIGH);
  Point p = ts.getPoint();
  digitalWrite(13, LOW);

  // if you're sharing pins, you'll need to fix the directions of the touchscreen pins!
  //pinMode(XP, OUTPUT);
  pinMode(XM, OUTPUT);
  pinMode(YP, OUTPUT);
  //pinMode(YM, OUTPUT);

  // we have some minimum pressure we consider 'valid'
  // pressure of 0 means no pressing!

  if (p.z > MINPRESSURE && p.z < MAXPRESSURE) {
    /*
    Serial.print("X = "); Serial.print(p.x);
    Serial.print("\tY = "); Serial.print(p.y);
    Serial.print("\tPressure = "); Serial.println(p.z);
    */
    if (p.y < (TS_MINY-5)) {
      Serial.println("Clear screen");
     // press the bottom of the screen to erase 
      tft.fillRect(0,  boxHeight, tft.width(), tft.height()-boxHeight, BLACK);
      drawBox();saveBox();loadBox();
    }
    // turn from 0->1023 to tft.width
    p.x = map(p.x, TS_MINX, TS_MAXX, tft.width(), 0);
    p.y = map(p.y, TS_MINY, TS_MAXY, tft.height(), 0);
    /*
    Serial.print("("); Serial.print(p.x);
    Serial.print(", "); Serial.print(p.y);
    Serial.println(")");
    */
    boolean changed = false;
    if ((p.x < boxWidth*1) && (p.y < boxHeight*8) && (p.y > boxHeight*7)){
      paused = !paused;  delay(200);  changed = true;
    }
    if (paused){
      if(changed){
        pauseBox();
      }
    } else if (p.y < boxHeight) {
      oldC = newC;
      paletteBox();
      newCbox(p.x);
    } else if ((p.x < boxWidth*1) && (p.y < boxHeight*6) && (p.y > boxHeight*5)){
      saveBmp();
    } else if ((p.x < boxWidth*1) && (p.y < boxHeight*5) && (p.y > boxHeight*4)){
      loadBmp();
    } else {
      penRadius =  analogRead(5);
      penRadius = map(penRadius, 0, 1023, 1, 5);

      if (((p.y-penRadius) > boxHeight) && ((p.y+penRadius) < tft.height())) {
        tft.fillCircle(p.x, p.y, penRadius, newC);
      }
      if (changed){
        drawBox();saveBox();loadBox();
      }
    }
  }
}

void newCbox(int xLoc){
  if (xLoc < boxWidth*1) { 
    newC = RED; 
    tft.drawRect(boxWidth*0, 0, boxWidth, boxHeight, WHITE);
  } else if (xLoc < boxWidth*2) {
    newC = YELLOW; 
    tft.drawRect(boxWidth*1, 0, boxWidth, boxHeight, WHITE);
  } else if (xLoc < boxWidth*3) {
    newC = GREEN; 
    tft.drawRect(boxWidth*2, 0, boxWidth, boxHeight, WHITE);
  } else if (xLoc < boxWidth*4) {
    newC = CYAN; 
    tft.drawRect(boxWidth*3, 0, boxWidth, boxHeight, WHITE);
  } else if (xLoc < boxWidth*5) {
    newC = BLUE; 
    tft.drawRect(boxWidth*4, 0, boxWidth, boxHeight, WHITE);
  } else if (xLoc < boxWidth*6) {
    newC = MAGENTA; 
    tft.drawRect(boxWidth*5, 0, boxWidth, boxHeight, WHITE);
  } else if (xLoc < boxWidth*7) {
    newC = BLACK; 
    tft.drawRect(boxWidth*6, 0, boxWidth, boxHeight, WHITE);
  } else if (xLoc < boxWidth*8) {
    newC = WHITE; 
    tft.drawRect(boxWidth*7, 0, boxWidth, boxHeight, RED);
  }
}

void paletteBox(){
  tft.fillRect(boxWidth*0, 0, boxWidth, boxHeight, RED);
  tft.fillRect(boxWidth*1, 0, boxWidth, boxHeight, YELLOW);
  tft.fillRect(boxWidth*2, 0, boxWidth, boxHeight, GREEN);
  tft.fillRect(boxWidth*3, 0, boxWidth, boxHeight, CYAN);
  tft.fillRect(boxWidth*4, 0, boxWidth, boxHeight, BLUE);
  tft.fillRect(boxWidth*5, 0, boxWidth, boxHeight, MAGENTA);
  tft.fillRect(boxWidth*6, 0, boxWidth, boxHeight, BLACK);
  tft.fillRect(boxWidth*7, 0, boxWidth, boxHeight, WHITE);
}

//  box(40, 100, 100, 30, 2047, 2016, 2078, 2, 3, "Yo");
void box(int x, int y, int h, int w,
  int boxBorderColor, int boxFillColor,
  int textColor, int textSize, int textRotation,
  String textText){
  tft.drawRect(x+0, y+0, w-0, h-0, boxBorderColor);
  tft.fillRect(x+1, y+1, w-2, h-2, boxFillColor);
  tft.drawRect(x+2, y+2, w-4, h-4, boxBorderColor);
  tft.setCursor(320-h-y+10, x+10);
  tft.setRotation(textRotation);
  tft.setTextColor(textColor);
  tft.setTextSize(textSize);
  tft.println(textText);
  tft.setRotation(0);
}

void saveBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*5+0, boxWidth-0, boxHeight-0, YELLOW);
  tft.fillRect(boxWidth*0+1, boxHeight*5+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*5+2, boxWidth-4, boxHeight-4, YELLOW);
  tft.setRotation(3);
  tft.setCursor(90, 12);
  tft.setTextColor(YELLOW);
  tft.setTextSize(1);
  tft.println("SAVE");
  tft.setRotation(0);
}

void loadBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*4+0, boxWidth-0, boxHeight-0, CYAN);
  tft.fillRect(boxWidth*0+1, boxHeight*4+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*4+2, boxWidth-4, boxHeight-4, CYAN);
  tft.setRotation(3);
  tft.setCursor(130, 12);
  tft.setTextColor(CYAN);
  tft.setTextSize(1);
  tft.println("LOAD");
  tft.setRotation(0);
}

void drawBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*7+0, boxWidth-0, boxHeight-0, GREEN);
  tft.fillRect(boxWidth*0+1, boxHeight*7+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*7+2, boxWidth-4, boxHeight-4, GREEN);
  tft.setRotation(3);
  tft.setCursor(10, 12);
  tft.setTextColor(GREEN);
  tft.setTextSize(1);
  tft.println("DRAW");
  tft.setRotation(0);
}

void pauseBox(){
  tft.drawRect(boxWidth*0+0, boxHeight*7+0, boxWidth-0, boxHeight-0, RED);
  tft.fillRect(boxWidth*0+1, boxHeight*7+1, boxWidth-2, boxHeight-2, BLACK);
  tft.drawRect(boxWidth*0+2, boxHeight*7+2, boxWidth-4, boxHeight-4, RED);
  tft.setRotation(3);
  tft.setCursor(5, 12);
  tft.setTextColor(RED);
  tft.setTextSize(1);
  tft.println("PAUSE");
  tft.setRotation(0);
}

/*********************************************/
// This procedure reads a bitmap and draws it to the screen
// its sped up by reading many pixels worth of data at a time
// instead of just one pixel at a time. increading the buffer takes
// more RAM but makes the drawing a little faster. 20 pixels' worth
// is probably a good place

#define BUFFPIXEL 20

void bmpdraw(File f, int x, int y) {
  bmpFile.seek(bmpImageoffset);
  
  uint32_t time = millis();
  uint16_t p;
  uint8_t g, b;
  int i, j;
  
  uint8_t sdbuffer[3 * BUFFPIXEL];  // 3 * pixels to buffer
  uint8_t buffidx = 3*BUFFPIXEL;
  
  Serial.print("rotation = "); Serial.println(tft.getRotation(), DEC);
  
  for (i=0; i< bmpHeight; i++) {
    // bitmaps are stored with the BOTTOM line first so we have to move 'up'

    if (tft.getRotation() == 3) {
      tft.goTo(x, y+bmpHeight-i); 
    } else if  (tft.getRotation() == 2) {
      tft.goTo(x+i, y);
    } else if  (tft.getRotation() == 1) {
        tft.goTo(x+bmpWidth-i, y+bmpHeight); 
    } else if  (tft.getRotation() == 0) {
      tft.goTo(x+bmpWidth, y+i); 
    }
    
    for (j=0; j<bmpWidth; j++) {
      // read more pixels
      if (buffidx >= 3*BUFFPIXEL) {
        bmpFile.read(sdbuffer, 3*BUFFPIXEL);
        buffidx = 0;
      }
      
      // convert pixel from 888 to 565
      b = sdbuffer[buffidx++];     // blue
      g = sdbuffer[buffidx++];     // green
      p = sdbuffer[buffidx++];     // red
      
      p >>= 3;
      p <<= 6;
      
      g >>= 2;
      p |= g;
      p <<= 5;
      
      b >>= 3;
      p |= b;
     
       // write out the 16 bits of color
      tft.writeData(p);
    }
  }
  Serial.print(millis() - time, DEC);
  Serial.println(" ms");
}

boolean bmpReadHeader(File f) {
   // read header
  uint32_t tmp;
  
  if (read16(f) != 0x4D42) {
    // magic bytes missing
    return false;
  }
 
  // read file size
  tmp = read32(f);  
  Serial.print("size 0x"); Serial.println(tmp, HEX);
  
  // read and ignore creator bytes
  read32(f);
  
  bmpImageoffset = read32(f);  
  Serial.print("offset "); Serial.println(bmpImageoffset, DEC);
  
  // read DIB header
  tmp = read32(f);
  Serial.print("header size "); Serial.println(tmp, DEC);
  bmpWidth = read32(f);
  bmpHeight = read32(f);

  
  if (read16(f) != 1)
    return false;
    
  bmpDepth = read16(f);
  Serial.print("bitdepth "); Serial.println(bmpDepth, DEC);

  if (read32(f) != 0) {
    // compression not supported!
    return false;
  }
  
  Serial.print("compression "); Serial.println(tmp, DEC);

  return true;
}

/*********************************************/

// These read data from the SD card file and convert them to big endian 
// (the data is stored in little endian format!)

// LITTLE ENDIAN!
uint16_t read16(File f) {
  uint16_t d;
  uint8_t b;
  b = f.read();
  d = f.read();
  d <<= 8;
  d |= b;
  return d;
}


// LITTLE ENDIAN!
uint32_t read32(File f) {
  uint32_t d;
  uint16_t b;
 
  b = read16(f);
  d = read16(f);
  d <<= 16;
  d |= b;
  return d;
}


