#include <JTC/JTC.h>
#include <iostream>
#include <time.h>

using namespace std;

#define MAX 40

class Posti : public JTCMonitor
{
	int posto[MAX];
public:
	int trovaEBloccaPosto(int codiceutente)
	{
		JTCSynchronized sync(*this);
		for(int i =0; i < MAX; i++)
			if (posto[i] == 0)
			{
				posto[i] = codiceutente;
				return i;
			}
		return -1;
	}
};
Posti* posti;

class StampaSync : public JTCMonitor

{
public:
	void stampa(int cod, int utente, int posto, bool esitoPos)
	{
		JTCSynchronized sync(*this);
        cout << "------" << endl;
		cout << "Banco checkin: " << cod <<endl;
		   if (esitoPos)
     	{
     		cout << "Prenotato posto: " << posto << " per utente " << utente << endl;
     	}
     	else
     		cout << "\tUtente: " << utente <<
     		" non c'è posto per te." << endl;
	}
};

StampaSync *stampaSync;

class BancoCheckin : public JTCThread

{
	int codiceBanco;
public:
	BancoCheckin (int cod)
	{ codiceBanco = cod; }
	virtual void run()
	{
		srand(codiceBanco*time(0));
		while(true)
		{
		   sleep(100);
		   int codiceutente = rand() % 10000;
		   int posto = posti->trovaEBloccaPosto(codiceutente);
		   stampaSync->stampa(codiceBanco,codiceutente,posto, posto > 0);
		}
	}
};

int main()
{
	JTCInitialize init;
	posti = new Posti();
	stampaSync = new StampaSync();
    BancoCheckin *a = new BancoCheckin(1);
    BancoCheckin *b = new BancoCheckin(2);
    BancoCheckin *c = new BancoCheckin(3);
    a->start();
    b->start();
    c->start();
    return 0;
}


