package candyfactory;

import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public abstract class CandyObject extends Thread{
    int x, y;

    int w, h;

    int quantity;

    int capacity;

    ReentrantLock lock = new ReentrantLock();

    Condition hasRoom = lock.newCondition();

    Condition hasCandies = lock.newCondition();

    public CandyObject(int x, int y, int w, int h, int capacity, int quantity) {
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
	this.capacity = capacity;
	this.quantity = quantity;
    }

    boolean contains(Truck t) {
	return new Rectangle(x, y, w, h).contains(t.x, t.y);
    }

    void loadUnload(Truck t) {
	if (t.full)
	    unload(t);
	else
	    load(t);
    }

    void load(Truck t) {
	lock.lock();
	while (t.capacity > quantity)
	    try {
		hasCandies.await();
	    } catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	quantity -= t.capacity;
	t.full = true;
	hasRoom.signalAll();
	lock.unlock();
    }

    void unload(Truck t) {
	lock.lock();
	while (t.capacity + quantity > capacity) {
	    try {
		hasRoom.await();
	    } catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	}
	quantity += t.capacity;
	t.full = false;
	hasCandies.signalAll();
	lock.unlock();
    }

    void drawSelf(Graphics g) {
	g.drawString(quantity + "/" + capacity, x, y);
    }
}
