package example.simulation;

import java.util.Random;

import example.entity.Person;

public class Simulation implements Runnable {


	private Driver parent = null;
	private Random rn = new Random();

	public Simulation(Driver parent) {
		this.parent = parent;
	}
	
	private int rand(int lo, int hi) {
        int n = hi - lo + 1;
        int i = rn.nextInt() % n;
        if (i < 0)
                i = -i;
        return lo + i;
}

	
	String getPossibleKey() {
		int which = rand(0,parent.getKeyList().size()- 1);

		return parent.getKeyList().get(which);	
	}

	
	@Override
	public void run() {
		
		System.out.println("Simulation started");
		long runLength = parent.getRunlength();		
		long start = System.currentTimeMillis();
		
		int hits =0;
		int misses = 0;
		int interations = 0;
		do {
			interations++;
			
			String key = getPossibleKey();
			Person p = (Person)parent.getNamedCache().get(key);
			if ( p != null) {
				hits++;
				p.touch();
				parent.setMaxTouchCount(p.getTouchCount());
				parent.getNamedCache().put(p.getKey(), p);
				if ( hits %500 == 0 )
					System.out.println("\n++++\n"+p.toString() + "\n++++\n");
				
			} else {
				misses++;
				if ( misses %100 == 0 )
					System.out.println("Did not find key '"+key+"'");
			}
				
			
			try { Thread.sleep(10); } catch (InterruptedException e) { }
			
			
			if ( interations %100 == 0 ) {
				System.out.print("*");
			}
			
		} while (  System.currentTimeMillis() - start < runLength);
		
		System.out.println("\n\nSimRuner completed");
			
		
	}

}
