import processing.core.*; 
import processing.xml.*; 

import java.awt.dnd.*; 
import java.awt.datatransfer.*; 
import javax.swing.*; 
import processing.pdf.*; 

import java.applet.*; 
import java.awt.*; 
import java.awt.image.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
import java.text.*; 
import java.util.*; 
import java.util.zip.*; 
import java.util.regex.*; 

public class sliced_pixels extends PApplet {


PImage img, bg;       // The source image
int cellsize = 8; // Dimensions of each cell in the grid
int cols, rows;   // Number of columns and rows in our system
String sImg = "pc.jpg"; 
int w, h;
boolean showBg = false; 
int treat;
int ani = 1;

public void setup() {
  
  //frame.setLocation(0,0);
  int treat = 0;
  println(sImg);

  int src_w = screen.width/3*2;
  int src_h = screen.height/3*2;
  
 
  //img  = loadImage(chooseFile());         // Load the image
  img  = loadImage(sImg);         // Load the image

  if((img.width / img.height) > (src_w / src_h)){
    img.resize(src_w, 0);
    w = src_w;
    h = img.height;
  }else{
    img.resize(0, src_h);
    w = img.width;
    h = src_h; 
  }

  //size(w, h, P3D);
  size(w, h); 
   frame.setSize(w, h);


  cols = w/cellsize;                  // Calculate # of columns
  rows = h/cellsize;                 // Calculate # of rows# 

  frameRate = 25;
  
  loop();

}
public void draw() { 
/*  
  //animation
  
  if(ani == 1){
  cellsize++;
  
  if(cellsize > 50) ani = 0; 
  }
  
  if(ani == 0){
    cellsize--;
    if(cellsize < 10){
      cellsize = 10;
      ani = 1;
    }
  }
  cols = w/cellsize;                  // Calculate # of columns
  rows = h/cellsize;                 // Calculate # of rows#  
 
  //-----------
  */
    
  //hint(DISABLE_DEPTH_SORT);


  if(showBg == true || sImg == "pc.jpg")background (img);
  else background(255);
  
  if(sImg != "pc.jpg"){
    
  record_PDF_start(); //start record
  
 
  // ++++++++++++ begin DRAW
      
int i = 0;
int j = 0;


for (  i = 0; i < rows;i++) {
    // Begin loop for rows
    for (  j = 0; j < cols;j++) { // pixel recursion
    
    int x = j*cellsize; // x position
    int y = i*cellsize; // y position
    int z = 0;
    
    
    int loc = x + y*width;           // Pixel array location
    if(loc < img.pixels.length){
    int c = img.pixels[loc];       // Grab Color 
    
    // 16 Bit
    float r = red(c);
    float g = green(c);
    float b = blue(c);
   
    float factor = 1;
   
    r = round(r/factor);
    r = r*factor;
    g = round(g/factor);
    g = g*factor;
    b = round(b/factor);
    b = b*factor;
    
    c = color(r,g,b);
    float gray = (r+g+b)/3;
    //c = color(gray,gray,gray);
    
    //+++++++++
    
    fill(c);
    noStroke();

//---------- TREATS ---------------
  if(treat == 0){  
    triangle (x+cellsize,y,x+cellsize,y+cellsize,x,y+cellsize);
    triangle (x+cellsize,y,x+cellsize,y+cellsize,x+(2*cellsize),y);
  }
  if(treat == 1){  
    triangle (x+cellsize,y,x+cellsize,y+cellsize,x,y+cellsize);
    triangle (x,y,x,y-cellsize,x+cellsize,y-cellsize);
  }
  if(treat == 2){  
    triangle (x+cellsize,y,x+cellsize,y+cellsize,x,y+cellsize);
  }
  if(treat == 3){  
    triangle (x+cellsize,y-cellsize,x,y,x,y-cellsize);
    triangle (x+cellsize,y-cellsize,x,y,x,y+cellsize);
  }
    
 //-------------------------
    }

    }   
  }
  
  // +++++++++++ end DRAW

  record_PDF_end(); //finish record
  } // End Of Image Check
}

public String ten(int x){
  if(x<10){
    return "0"+Integer.toString(x);
  }else{
    return Integer.toString(x);
  }
}




DropTarget dt = new DropTarget(this, new DropTargetListener() {
 public void dragEnter(DropTargetDragEvent event) {
   // debug messages for diagnostics
   //System.out.println("dragEnter " + event);
   event.acceptDrag(DnDConstants.ACTION_COPY);
 }

 public void dragExit(DropTargetEvent event) {
   //System.out.println("dragExit " + event);
 }

 public void dragOver(DropTargetDragEvent event) {
   //System.out.println("dragOver " + event);
   event.acceptDrag(DnDConstants.ACTION_COPY);
 }

 public void dropActionChanged(DropTargetDragEvent event) {
   //System.out.println("dropActionChanged " + event);
 }

 public void drop(DropTargetDropEvent event) {
   //System.out.println("drop " + event);
   event.acceptDrop(DnDConstants.ACTION_COPY);

   Transferable transferable = event.getTransferable();
   DataFlavor flavors[] = transferable.getTransferDataFlavors();
   int successful = 0;

   for (int i = 0; i < flavors.length; i++) {
     try {
       Object stuff = transferable.getTransferData(flavors[i]);
       if (!(stuff instanceof java.util.List)) continue;
       java.util.List list = (java.util.List) stuff;

       for (int j = 0; j < list.size(); j++) {
         Object item = list.get(j);
         if (item instanceof File) {
           File file = (File) item;

          
           String filename = file.getPath();
           noLoop();
           sImg = filename;
           setup();
         }
       }

     } 
     catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
}
);
  

String image_path;

public String chooseFile(){
  image_path = sImg;
// set system look and feel
try {
  UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
  e.printStackTrace(); 
}

//Create a file chooser
final JFileChooser fc = new JFileChooser();

//In response to a button click:
int returnVal = fc.showOpenDialog(this);

if (returnVal == JFileChooser.APPROVE_OPTION) {
  File file = fc.getSelectedFile();
  // see if it's an image
  // (better to write a function and check for all supported extensions)
    image_path = file.getPath();
} 
else {
  println("Open command cancelled by user.");
}
return image_path;
}


public void keyPressed() { // FOR Recording  >> press r
  // use a key press so that it doesn't make a million files
  //println(key);
  println (key + ":" + PApplet.parseInt(key));
  int ascii = PApplet.parseInt(key);
  if (key == 'p') record_PDF = true;
  if (key == ' '){
    noLoop();
     setup();
  }
  if (key == 'n'){
    noLoop();
    sImg = chooseFile();
     setup();
  }
  if (key == '+'){
    cellsize++;
  cols = w/cellsize;                  // Calculate # of columns
  rows = h/cellsize;                 // Calculate # of rows#     
  }
  if (key == '-'){
    cellsize--;
    if(cellsize < 2)cellsize = 2;
  cols = w/cellsize;                  // Calculate # of columns
  rows = h/cellsize;                 // Calculate # of rows#     
  }
  if (key == 'b'){
   if(showBg == true)showBg = false;
   else showBg = true;  
  }
  
  if (ascii > 48 && ascii < 53){
    treat = ascii - 49; 
    println (treat);
  }
}


boolean record_PDF;

/*
void record_PDF_start(){
  if (record_PDF) {
     int out_year = year();
     int out_month = month();
     int out_day = day();
     int out_hour = hour();
     int out_minute = minute();
     int out_second = second();
     String prefix = out_year +"-"+ ten(out_month) +"-"+ ten(out_day) +"_"+ ten(out_hour) +"."+ ten(out_minute) +"."+ ten(out_second) +"--";
     beginRaw(PDF, "outputs/pdf/"+ prefix +"output.pdf");
  }
  
}

void record_PDF_end(){
  if (record_PDF) {
    endRaw();
    record_PDF = false;
  }
}
*/

public void record_PDF_start(){
  if (record_PDF) {
    frame.setTitle("Save PDF ...");
     int out_year = year();
     int out_month = month();
     int out_day = day();
     int out_hour = hour();
     int out_minute = minute();
     int out_second = second();
     String prefix = out_year +"-"+ ten(out_month) +"-"+ ten(out_day) +"_"+ ten(out_hour) +"."+ ten(out_minute) +"."+ ten(out_second) +"--";
     noLoop();
     beginRecord(PDF, "outputs/pdf/"+ prefix +"output.pdf");
     frame.setTitle("FILE SAVED");
     delay(500);
     loop();
  }
  
}

public void record_PDF_end(){
  if (record_PDF) {
    endRecord();
    record_PDF = false;
  }
}


  static public void main(String args[]) {
    PApplet.main(new String[] { "--bgcolor=#F0F0F0", "sliced_pixels" });
  }
}
