package particlefiltering;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;

import parameters.tracking_arguments;

import regrouping.Box;



public class pfTracking {
	
	
	public void Initialization ( 
			BufferedImage image, 
			int x,
			int y,
			int width,
			int height,
			ArrayList<particle[]> particles_list , 
			int box_id, 
			tracking_arguments tracking_parameters) throws FileNotFoundException, ClassNotFoundException, IOException {
		
		pRegion r = new pRegion();
			
		r.set_x(x); 
		
		r.set_y(y); 
		
		r.set_width(width);  
		
		r.set_height(height);
					
		observation obs = new observation();
		
		pHistogram ref_histo = obs.compute_ref_histos (image, tracking_parameters);
		
		particles pobj = new particles();
		
		particle[] particles = pobj.init_distribution (r, ref_histo, tracking_parameters.number_of_particles); 
		
		/*try {
			BufferedImage tmp = image.getSubimage (x, y, width, height);
	   		 ImageIO.write(tmp, "png", new File("box_"+String.format("%02d", box_id)+".png"));
	      	}
			catch (Exception exception) {
	   		 System.err.println("error: write image exception!");
		}*/
		
		particles_list.add (box_id, particles);
		
	}
	
	public void Tracking (BufferedImage image, ArrayList<particle[]> particles_list, int num_boxes, int frame_number, tracking_arguments tracking_parameters) {

		ArrayList<pfThread> threadList = new ArrayList<pfThread>();
		
		pfThread thread = null;
		
		for (int box = 0; box < num_boxes; box++) { 
			thread = new pfThread(image, particles_list.get(box), frame_number, box, tracking_parameters);
			threadList.add(thread);
			thread.start();
		}

		boolean flag = true;
		
		while (flag) {
			flag = false;
			for(pfThread t : threadList) {
				if(!t.hasFinished()) {
					flag = true;
				}
			}	
			Thread.yield();
		} 

		for (int box = 0; box < num_boxes; box++) {
			particles_list.set(box, threadList.get(box).getParticles());
		}	
	}
}
