#include "HistorieSender.h"
#ifdef WIN32
#include "../SpielServer.h"
#else
#include "SpielServer.h"
#endif
#include <Datei.h>

// Inhalt der HistorieSender Klasse aus HistorieSender.h
// Konstruktor
HistorieSender::HistorieSender( SpielServer *zSS )
{
	this->zSS = zSS;
	beenden = 0;
	ref = 1;
}

// Destruktor
HistorieSender::~HistorieSender()
{
}

// nicht constant
void HistorieSender::setEnde()
{
	beenden = 1;
}

void HistorieSender::thread()
{
	Datei *d = new Datei();
	d->setDatei( "../spiel log" );
	while( !beenden )
	{
		Sleep( 10000 );
		int anz = d->getUnterdateiAnzahl();
		RCArray< Text > *list = d->getDateiListe();
		int min = 0;
		for( int i = 0; i < anz; i++ )
		{
			if( !list->z( i ) )
				continue;
			Text pf( d->zPfad()->getText() );
			pf += "/";
			pf += list->z( i )->getText();
			pf += "/fertig";
			if( !DateiExistiert( pf ) )
				continue;
			if( !min || min >( int )*list->z( i ) )
				min = *list->z( i );
		}
		list->release();
		if( min )
		{
			short port = 0;
			Text *ip = new Text();
			if( zSS->zDB()->suchHistorieServer( &port, ip ) )
			{
				Klient *k = new Klient();
				unsigned char key[ 20 ] = { 207, 30, 72, 46, 30, 50, 56, 213, 82, 107, 14, 201, 149, 58, 110, 138, 228, 241, 52, 54 };
				k->setSendeKey( (char*)key, 20 );
				k->setEmpfangKey( (char*)key, 20 );
				if( k->verbinde( port, *ip ) )
				{
					zSS->addSpielHistorieId( min );
					unsigned char ret = 0;
					k->sendeEncrypted( "\5", 1 );
					k->getNachrichtEncrypted( (char*)&ret, 1 );
					if( ret == 1 )
					{
						int server = zSS->getId();
						k->sendeEncrypted( (char*)&server, 4 );
						k->sendeEncrypted( (char*)&min, 4 );
						k->getNachrichtEncrypted( (char*)&ret, 1 );
						if( ret == 1 )
							DateiRemove( Text( "../spiel log/" ) += min );
					}
					if( ret == 3 )
					{
						k->getNachrichtEncrypted( (char*)&ret, 1 );
						char *err = new char[ ret ];
						k->getNachrichtEncrypted( err, ret );
						delete[] err;
					}
					k->sendeEncrypted( "\3", 1 );
					k->getNachrichtEncrypted( (char*)&ret, 1 );
					k->trenne();
					k->release();
					zSS->removeSpielHistorieId( min );
				}
			}
			ip->release();
		}
	}
	d->release();
	run = 0;
}

// Reference Counting
HistorieSender *HistorieSender::getThis()
{
	ref++;
	return this;
}

HistorieSender *HistorieSender::release()
{
	ref--;
	if( !ref )
		delete this;
	return 0;
}