package edu.columbia.cs.education.kaleidoscope;

import java.applet.Applet;
import java.awt.*;

public class Kaleidoscope extends Applet implements Runnable {

  Swipe swipethread;
  Thread mainthread;
  int width, height;
  int iteration = 1;


  public void init() {

    width = getWidth();
    height = getHeight();
  }


  public void start() {
    if (swipethread == null) {
      swipethread = new Swipe();
      swipethread.start();
    }
    if (mainthread == null) {
      mainthread = new Thread(this);
      mainthread.start();
    }
  }


  public void stop() {
    if (swipethread != null) {
      swipethread.stop();
      swipethread = null;
    }
    if (mainthread != null) {
      mainthread.stop();
      mainthread = null;
    }
  }


  public void run() {
    while (true) {
      try {
	mainthread.sleep(100);
      }
      catch (InterruptedException e) {
      }
      super.repaint();
    }
  }


  public void paint(Graphics g) {

    Color color = new Color(0, 0, 0);
    g.setColor(color);
    g.fillRoundRect(0, 0, width, height, 0, 0);
  }


  public void update(Graphics g) {

    int x1 = 0, x2 = 0, y1 = 1, y2 = 1;
    int hwidth = width / 2, hheight = height / 2;

    iteration++;
    if (iteration == 50)
      iteration = 1;
    Color color = new Color((int)(Math.random() * 255),
			    (int)(Math.random() * 255),
			    (int)(Math.random() * 255));
    g.setColor(color);

    while ((x1 < (4 * y1 / 3)) && (x2 < (4 * y2 / 3))) {
      x1 = (int)(Math.random() * (hwidth));
      y1 = (int)(Math.random() * (hheight));
      x2 = (int)(Math.random() * (hwidth));
      y2 = (int)(Math.random() * (hheight));
    }
    int step1 = (int)(Math.random() * 4);
    int step2 = (int)(Math.random() * 4);
    for (int loopvar = 1; loopvar < 40; loopvar++) {
      x1 = x1 + step1;
      x2 = x2 + step2;
      y1 = y1 + step1;
      y2 = y2 + step2;
      g.drawLine(x1, y1, x2, y2);
      g.drawLine(width - x1, height - y1, width - x2, height - y2);
      g.drawLine(width - x1, y1, width - x2, y2);
      g.drawLine(x1, height - y1, x2, height - y2);
      g.drawLine(hwidth - x1, hheight - y1, hwidth - x2, hheight - y2);
      g.drawLine(hwidth + x1, hheight + y1, hwidth + x2, hheight + y2);
      g.drawLine(hwidth - x1, hheight + y1, hwidth - x2, hheight + y2);
      g.drawLine(hwidth + x1, hheight - y1, hwidth + x2, hheight - y2);
    }

    if (iteration == 1) {
      width = getWidth();
      height = getHeight();
      swipethread.Swipe(g, width, height);
    }

  }

}