package G1.market_final;

import java.awt.Graphics;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Market implements Drawable {
	private int x, y, w, h;
	private int c, q; // quantity (q) je deljeni resurs
	private ReentrantLock rlock = new ReentrantLock();
	private Condition isNotFull = rlock.newCondition(); // ovde cekaju oni
														// trgovci koji hoce da
														// prodaju
	private Condition isNotEmpty = rlock.newCondition(); // cekaju oni koji
															// pokusavaju da
															// kupe

	public Market(int x, int y, int w, int h, int c, int q) {
		super();
		this.x = x;
		this.y = y;
		this.w = w;
		this.h = h;
		this.c = c;
		this.q = q;
	}

	@Override
	public void drawSelf(Graphics g) {
		g.drawRect(x, y, w, h);
		g.drawString(q + "", x + w / 2 - 3, y + h / 2 - 3);
	}

	public boolean contains(int x2, int y2) {
		return (x2 >= x && x2 <= x + w && y2 >= y && y2 <= y + h);
	}

	private void sell(Salesman salesman) {
		rlock.lock();
		while (q < salesman.getCapacity())
			try {
				isNotEmpty.await();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		q -= salesman.getCapacity();
		salesman.setFull(true);
		isNotFull.signalAll();
		rlock.unlock();
	}

	private void buy(Salesman salesman) {
		rlock.lock();
		while(q+salesman.getCapacity()>c)
			try {
				isNotFull.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		q += salesman.getCapacity();
		salesman.setFull(false);
		isNotEmpty.signalAll();
		rlock.unlock();
	}

	public void doSale(Salesman salesman) {
		if (salesman.isFull())
			buy(salesman);
		else
			sell(salesman);
	}

	public int getX() {
		return x;
	}

	public int getW() {
		return w;
	}

	public int getY() {
		return y;
	}

	public int getH() {
		return h;
	}
}
