

#include <JTC/jtc.h>
#include <time.h>
#include <iostream>

using namespace std;

int getTime()

{
	return time(0);
}



class Lock : public JTCMonitor

{
	bool occupato;
public:
	void lock()
	{
		JTCSynchronized sync(*this);
		while(occupato)
			wait();
		occupato = true;
	}
	void unlock()
	{
		JTCSynchronized sync(*this);
		occupato = false;
		notifyAll();
	}
};
Lock coutSync;


enum tipoMessaggio { GPS, IMMAGINE };

class Messaggio
{
public:
	tipoMessaggio codice;
	int codiceThread;
	void* dato;
	Messaggio(tipoMessaggio cod, int codThread, void* d)
	{
		codice = cod;
		codiceThread = codThread;
		dato = d;
	}
};


#define LEN 40
template <class T>
class BufferPrivato : public JTCMonitor

{
protected:

	T thebuffer[LEN];
	int in;
	int out;
	int chars;

public:
	BufferPrivato(T initValue = 0)
	{
		in = 0;
		out = 0;
		chars = 0;
		for(int i = 0; i < LEN; i++)
			thebuffer[i] = initValue;
	}

	T get()
	{
		T c = thebuffer[out];
		//cout << this << " Getting:" << c << " in=" << in << " out=" << out << " Chars=" << chars << endl;
		out = ( out + 1 ) % LEN;
		chars--;
		return c;
	}

	void put(T c)
	{
		//cout << this << " Putting:" << c << " in=" << in << " out=" << out << " Chars=" << chars <<endl;
		chars++;
        thebuffer[in] = c;
		in = (in + 1) % LEN;
	}
	bool vuota()
	{ return chars == 0; }
};


template <class T>
class BufferCondiviso : public BufferPrivato<T>
{

public:
	BufferCondiviso(T initValue = 0) : BufferPrivato<T>(initValue)
	{}

	T get()
	{
		JTCSynchronized sync(*this);
		while (BufferPrivato<T>::chars == 0) {
			JTCMonitor::wait();
		}
		return ((BufferPrivato<T>*)this)->get();
	}

	void put(T c)
	{
		JTCSynchronized sync(*this);
		while (BufferPrivato<T>::chars == LEN) {
			JTCMonitor::wait();
		}
		((BufferPrivato<T>*)this)->put(c);
		JTCMonitor::notifyAll();
	}
};

typedef BufferCondiviso<Messaggio*> CodaCondivisa;
typedef BufferPrivato<Messaggio*> CodaPrivata;



class DatoGPS

{
public:
    double latitudine;
    double longitudine;
    int dataRilevamento;
    DatoGPS(double lat, double lon, int data) : latitudine(lat), longitudine(lon), dataRilevamento(data) {};
};

class Immagine
{
public:
	char* dati;
	int dataScatto;
	double latitudine;
	double longitudine;
    Immagine(char* d,int data) : dati(d), dataScatto(data) {};
};


class CameraThread : public JTCThread
{
     CodaCondivisa* c;
     int codiceCamera;
public:
    CameraThread(int codiceCamera, CodaCondivisa* c)
	{
		this->c = c;
		srand(time(0));
		this->codiceCamera = codiceCamera;
	}
	virtual void run()
	{
		while(true) {
			int t = rand() % 2500;
			coutSync.lock();
			cout << "--CameraThread " << codiceCamera << "--S=" << t << endl;
			coutSync.unlock();
			sleep(t);
			c->put(new Messaggio(IMMAGINE, codiceCamera,new Immagine(0,getTime())));
			}
	}

};

#define DELTA 0.01

class GPSThread : public JTCThread

{
	double latitudine;
	double longitudine;
	CodaCondivisa* c;

public:
	GPSThread(CodaCondivisa* c)
	{
		latitudine = rand() % 180 - 90;
		longitudine = rand() % 360 - 180;
		this->c = c;
		srand(time(0));
	}

	virtual void run()
	{
		while(true) {
		//
		//  modifica posizione corrente di un valore casuale
		//
		latitudine  += (rand() % 10 - 10) * DELTA;
		longitudine += (rand() % 10 - 10) * DELTA;
		//
		//  Qui mettere codice che arrotonda nel caso i valori escano dal range ammesso
		//  -90 +90 per latitudine
		//  -180 +180 per longitudine
		//
        // ...
		//
        c->put(new Messaggio(GPS,0,new DatoGPS(latitudine,longitudine,getTime())));
		coutSync.lock();
		cout << "--GPSTHREAD--\n";
		coutSync.unlock();

        sleep(5000);
		}
	}
};


class GeoTagThread : public JTCThread

{
	double ultimaLat;
	double ultimaLong;
	int  tempoUltimoGPS;
	double precLat;
	double precLong;
	bool primoDato;
	int tempoPrecGPS;
	CodaPrivata* codaPrivata;
	CodaCondivisa* codaComune;

public:
	GeoTagThread(CodaCondivisa* c)
	{
		codaComune = c;
		codaPrivata = new CodaPrivata();

	}
	virtual void run() {
        Messaggio* m;
    	while (true)
		{
			m = codaComune->get();
			coutSync.lock();
			cout << "Message from" << m->codiceThread << endl;
			coutSync.unlock();

			if (m->codice == GPS)
			{
				precLat = ultimaLat;
				precLong = ultimaLong;
				tempoPrecGPS = tempoUltimoGPS;
				ultimaLat = ((DatoGPS*)(m->dato))->latitudine;
				ultimaLong = ((DatoGPS*)(m->dato))->longitudine;
				tempoUltimoGPS = ((DatoGPS*)(m->dato))->dataRilevamento;

				//
				//  Pone come identici ultimo e penultimo rilevamento alla prima lettura
				//
				if( primoDato )
                {
                    primoDato = false;
                    precLat = ultimaLat;
                    precLong = ultimaLong;
                }
				//
				// Elabora le immagini acquisite tra un rilevamento GPS e l'altro
				//

				while(!codaPrivata->vuota())
				{
					Messaggio* n = codaPrivata->get();
					Immagine* imm = (Immagine*)(n->dato);
					//
					// Assegna le coordinate dell'ultimo rilevamento GPS temporalmente pił vicino
					//
					if ( abs(imm->dataScatto - tempoUltimoGPS) < abs(imm->dataScatto - tempoPrecGPS) )
					{
						imm->latitudine = ultimaLat;
						imm->longitudine = ultimaLong;
					}
					else
					{
						imm->latitudine = precLat;
						imm->longitudine = precLong;
					}
					coutSync.lock();
					cout << "--GEOTAGTHREAD-\n";
					cout << "Immagine proveniente da M" << n << "-" << n->codiceThread << endl;
					cout << "DataScatto:" << imm->dataScatto << endl;
					cout << "Posizione Geografica: LAT=" << imm->latitudine << " LONG=" << imm->longitudine << endl;
					cout << "---------------\n";
					coutSync.unlock();
				}
			}
			else
			// Codice == IMMAGINE
			{
				//
				//  Salva il messaggio contenente l'immagine per successiva elaborazione
				//
				codaPrivata->put(m);
			} // big if
		}
    }
};

class GeoTaggingModule
{
	CameraThread* M1;
	CameraThread* M2;
	GPSThread* g;
	CodaCondivisa* c;
	GeoTagThread* geo;

public:
	GeoTaggingModule()
	{
		c = new CodaCondivisa();
		M1 = new CameraThread(1,c);
		M2 = new CameraThread(2,c);
		g = new GPSThread(c);
		geo = new GeoTagThread(c);
		M1->start();
		M2->start();
		g->start();
		geo->start();
	}

};


int main()
{
   JTCInitialize init;
   GeoTaggingModule* module = new GeoTaggingModule();
   return 0;
}



