package reservationManager;
import javax.swing.Timer;
import java.awt.event.*;
import java.util.*;

/*
 * Implements a special timer that receives a dictionary with a key
 * and a resource object
 * and when the timer default timeout expires, we delete the entry from the dict
 * (the reservation entry) and added to the resource the ammount that was reserved in this entry
 *  
 * In such a way every reservation is watched and is removed
 * if not renewed at the right time
 */
public class clearingTimer extends Timer{
	private static int delay=40000;
	private Dictionary dict;
	private Object key;
	private Resource resource;
	private boolean isUsing = false;
	
	public clearingTimer(Dictionary dict, Object key, Resource resource){
		super(clearingTimer.delay,null);
		this.key = key;
		this.resource = resource;
		this.dict = dict;
		this.addActionListener(new MyListener(this));
	}
	
	/**
	 * Marks that the timer is marked for 
	 * resource that is already in use.
	 * no restarts are allowed if the flag is on.
	 * So the user who once used the resource wont be able to
	 * renew it all the time
	 */
	public void setInUse(){
		this.isUsing = true;
	}
	
	/**
	 * we override the stop method to perform the needed
	 * manipulations on the resource and the reservation db
	 */
	public void stop(boolean printMessage){
		int freed = freeResources();
		
		if (printMessage){
			if (this.isUsing)
				System.out.println("Finished using reservation "+key+". Freeing " + freed+ " resources");
			else
				System.out.println("reservation "+key+" expired");
		}
		System.out.println("availableResource = "+resource.getAmount()+"\n");
		super.stop();
	}
	
	/**
	 * frees all the resources that this watchdog thread is watching
	 * @return the amount that was freed
	 */
	
	public int freeResources(){
		DBEntry entry = (DBEntry)dict.get(key);
		//return the reserved ammount of the resource
		resource.returnResource(entry.data);
		//delete the reservation
		dict.remove(key);
		return entry.data;
	}
	
	/**
	 * we override the original restart method, 
	 * and disable the restart for Timer that was marked as watching a resource
	 * that is in use
	 */
	public void restart(){
		if (this.isUsing==false)
			super.restart();
	}
	
	public static void main(String[] args) {
		System.out.println("before");
		clearingTimer t = new clearingTimer(new Hashtable(),new Integer(2),new Resource(100));
		t.start();	
        System.out.println("ended");
	}
}


/**
 * the listened on the timer expiry event
 * receives the timer itself as the param, and calls its stop method
 * 
 */
class MyListener implements ActionListener{
	public clearingTimer toStop;
	private int count = 0;
	public MyListener(clearingTimer timer){
		this.toStop = timer;
	}
	
	public void actionPerformed(ActionEvent evt){
		//System.out.println(count+"..");
		count+=1;
		this.toStop.stop(true);
	}
};

