import java.applet.*;
import java.awt.*;
import Raster;
import Sprite;
import Playfield;

/**
 *  Project #1
 *  6.837 - F98
 *  Stephen J. Rhee
 *  mystery@mit.edu
 *
 *  @author Stephen J. Rhee
 *  @version 1.0
 */

public class Project1 extends Applet implements Runnable {
  Playfield playfield;
  AnimatedSprite sprite1;
  AnimatedSprite sprite2;
  Raster bg;
  Image bgimg;
  Image s1img, s2img;
  Image output;
  Thread animate;
  int drag, dragx, dragy;

  public void init() {
    drag = -1;
    bgimg = this.getImage(this.getCodeBase(), this.getParameter("image0"));
        bg = new Raster(bgimg);
    s1img = this.getImage(this.getDocumentBase(), this.getParameter("image1"));
    s2img = this.getImage(this.getDocumentBase(), this.getParameter("image2"));
    sprite1 = new AnimatedSprite(s1img, 12);
    sprite2 = new AnimatedSprite(s2img);
    playfield = new Playfield(bg.toImage(), 2);
    playfield.addSprite(0, sprite1);
    playfield.addSprite(1, sprite2);
    renderPlayfield();
  }
  
  public void start() {
    animate = new Thread(this);
    animate.start();
  }
  
  public void stop() {
    animate = null;
  }
  
  public void run() {
    while (true) {
      try {
	animate.sleep(1000);
      } catch (InterruptedException e) {
      }
      animatePlayfield();
    }
  }

  public void animatePlayfield() {
    sprite1.nextState();
    playfield.moveSprite(1, playfield.sprite[1].x, playfield.sprite[1].y);
    output = playfield.toImage();
    repaint();
  }

  public void updatePlayfield(int sn, int oldx, int oldy) {
    playfield.moveSprite(sn, oldx, oldy);
    output = playfield.toImage();
    repaint();
  }

  public void renderPlayfield() {
    playfield.Draw();
    output = playfield.toImage();
    repaint();
  }

  public void paint(Graphics g) {
    g.drawImage(output, 0, 0, this);
  }

  public void update(Graphics g) {
    paint(g);
  }
  
  public boolean mouseDown(Event e, int x, int y) {
    drag = playfield.isSprite(x, y);
    if (drag >= 0) {
      showStatus("non-transparent");
      dragx = x - playfield.sprite[drag].x;
      dragy = y - playfield.sprite[drag].y;
    }
    else if (drag == -2)
      showStatus("transparent");
    else showStatus("no sprite");
    return true;
  }

  public boolean mouseUp(Event e, int x, int y) {
    drag = -1;
    return true;
  }

  public boolean mouseDrag(Event e, int x, int y) {
    if ((x >= 0) && (x < playfield.getWidth()) &&
	(y >= 0) && (y < playfield.getHeight())) {
      if (drag >= 0) {
	int oldx = playfield.sprite[drag].x;
	int oldy = playfield.sprite[drag].y;
	playfield.sprite[drag].x = x - dragx;
	playfield.sprite[drag].y = y - dragy;
	updatePlayfield(drag, oldx, oldy);
      }
    }
    return true;
  }

}
