
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.jgrapht.*;
import org.jgrapht.graph.*;
import peasy.test.*;
import peasy.org.apache.commons.math.*;
import peasy.*;
import peasy.org.apache.commons.math.geometry.*;
import codeanticode.glgraphics.*;
import processing.opengl.*;
import codeanticode.gsvideo.GSMovieMaker;

public static final int CARS = 10;
public static final int WIDTH = 1200;
public static final int HEIGHT = 900;
List<Car> cars;
//RoadNet network;
Random r = new Random();
SloRoads network;
List<RoadEdge> roads;
Cars traffic;
Buildings buildings;
PeasyCam cam;
int dX = 0;
int dY = 0;
RoadVertex bRoute, eRoute, turret;
boolean firstSelected, secondSelected = false;
GSMovieMaker mm;

public void setup() {
  size(WIDTH, HEIGHT, GLConstants.GLGRAPHICS);
  
  int fps = 30;
  final String root = "C:\\Users\\solipsy\\Documents\\!Data\\video\\";
  float fov = PI/3.0;
  float cameraZ = (height/2.0) / tan(fov/2.0);
  perspective(fov, float(width)/float(height), cameraZ/30.0, cameraZ*100.0);
  cam = new PeasyCam(this, 2000);
  background(0);
  stroke(255);
  fill(255);
  network = new SloRoads(this);
  println ("roads ok");
  buildings = new Buildings(this);
  println ("buildings ok");
  traffic = new Cars(this, network);
  println ("traffic ok");
  mm = new GSMovieMaker(this, width, height, root + "eternal1.avi", GSMovieMaker.MJPEG, GSMovieMaker.MEDIUM, fps);
  mm.setQueueSize(50, 10);
  mm.start();
}

public void draw() {
  background(0);
  network.drawGL();
  List <Car> cars = traffic.getAllCars();
  buildings.drawGL(mouseX - width/2, mouseY - height/2, cars); //cars
  traffic.onRoute();
  showRoute ();
  loadPixels();
  mm.addFrame(pixels);
}

public void showRoute () {
  int segment = (int) (mouseX * (2000.0f / cam.getDistance()) / (width / 50))
    + 50
      * (int) (mouseY * (2000.0f / cam.getDistance()) / (height / 50));

  List<RoadVertex> vvv = network.getSegments().get(segment);
  if (vvv != null) {
    RoadVertex xy = vvv.get(0);
    fill(255, 0, 0);
    stroke(255, 0, 0);
    rect(xy.getX(), xy.getY(), 15, 15);
    fill(0, 0, 0);
    stroke(255, 255, 255);
    if (mousePressed && !firstSelected) {
      bRoute = xy;
      firstSelected = true;
    }
    if (mousePressed && (mouseButton == RIGHT)) {
      firstSelected = false;
    }

    if (firstSelected) {
      eRoute = xy;
      List<RoadEdge> rrr = network.getRoute(bRoute.getId(), 
      eRoute.getId());
      if (rrr != null) {
        for (RoadEdge rr : rrr) {
          rr.drawDebug();
        }
      }
    }
  }


  // for (float[] v : vvv) {
  // float[] xy = v;
  // fill(255, 0, 0);
  // stroke(255, 0, 0);
  // rect(xy[0], xy[1], 5, 5);
  // fill(0, 0, 0);
  // stroke(255, 255, 255);
  // }
  // }
}

  void keyPressed () {
    if (key == 'a') {
      // Finish the movie if a is pressed
      mm.finish();
      // Quit running the sketch once the file is written
    }
  }

