import processing.core.*; 
import processing.data.*; 
import processing.event.*; 
import processing.opengl.*; 

import sojamo.drop.*; 

import java.util.HashMap; 
import java.util.ArrayList; 
import java.io.File; 
import java.io.BufferedReader; 
import java.io.PrintWriter; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.io.IOException; 

public class sketch_jan18a extends PApplet {



SDrop drop;
boolean imLoaded=false;
boolean nmLoaded=false;

PImage im;
PImage nm;
PImage imG;
PImage imD;
PImage imF;

int sizx;
int sizy;

float decal;

public void setup() {
  size(300,100);
  drop = new SDrop(this);  
  noStroke();  
}

public void draw() {
  background(0);
  if (nmLoaded) {
    decal=(mouseX-(width/2))*50/(width/2);
    fill(255,0,0);
    rect(width/2-(decal*(width/2)/50)-5,0,10,height);
    fill(0,255,255);
    if (abs(mouseX-width/2)<5) {
      fill(255);
    }
    rect(width/2+(decal*(width/2)/50)-5,0,10,height);
  }
}

public void process() {
  sizx=im.width;
  sizy=im.height;
  imG=createImage(sizx, sizy, RGB);
  imD=createImage(sizx, sizy, RGB);
  imF=createImage(sizx, sizy, RGB);  
  boolean[][] poseeG=new boolean[sizx][sizy];  
  boolean[][] poseeD=new boolean[sizx][sizy];    
  for (int x=0;x<sizx;x++) {
    for (int y=0;y<sizy;y++) {    
      poseeG[x][y]=false;
      poseeD[x][y]=false;      
    }
  }
  for (int x=0;x<sizx;x++) {
    for (int y=0;y<sizy;y++) {
      float dec=(brightness(nm.get(x,y))*decal/256)-(decal/2);
      if (PApplet.parseInt(x-dec)>=0 && PApplet.parseInt(x-dec)<sizx) poseeG[PApplet.parseInt(x-dec)][y]=true;
      if (PApplet.parseInt(x+dec)>=0 && PApplet.parseInt(x+dec)<sizx) poseeD[PApplet.parseInt(x+dec)][y]=true;
      imG.set(PApplet.parseInt(x-dec),y,im.get(x,y));
      imD.set(PApplet.parseInt(x+dec),y,im.get(x,y));
    }
  }
  int cPG=im.get(0,0);
  int cPD=im.get(0,0);
  for (int y=0;y<sizy;y++) {  
    for (int x=0;x<sizx;x++) {
      if (!poseeG[x][y]) {
        imG.set(x,y,cPG);
      }
      else{
        cPG=imG.get(x,y);
      }
      if (!poseeD[x][y]) {
        imD.set(x,y,cPD);
      }
      else{
        cPD=imD.get(x,y);
      }      
    }
  }  
  background(0);
  for (int x=0;x<sizx;x++) {
    for (int y=0;y<sizy;y++) {
      imF.set(x,y,color(brightness(imG.get(x,y)),brightness(imD.get(x,y)),brightness(imD.get(x,y))));
    }
  }
  imF.save("result.png");
  imG.save("gauche.png");
  imD.save("droite.png");
}

public void dropEvent(DropEvent theDropEvent) {
  if (!imLoaded) {
    imLoaded=true;
    im=loadImage(theDropEvent.toString());
  } 
  else{
    nmLoaded=true;    
    nm=loadImage(theDropEvent.toString());
  }
}

public void mousePressed() {
  process();
}


  static public void main(String[] passedArgs) {
    String[] appletArgs = new String[] { "sketch_jan18a" };
    if (passedArgs != null) {
      PApplet.main(concat(appletArgs, passedArgs));
    } else {
      PApplet.main(appletArgs);
    }
  }
}
