// ------------------------------------------------
// File : lsys.cpp
// Date: 4-apr-2002
// Author: giles
// Desc: 
//		LSys derives from Sys to provide basic Linux functions such as starting threads.
//
// (c) 2002 peercast.org
// ------------------------------------------------
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// ------------------------------------------------


#include <time.h>
#include <pthread.h>
#include <signal.h>
#include <stdlib.h>
#include "lsys.h"
#include "lsocket.h"
#include "stats.h"

// ---------------------------------
LSys::LSys()
{
	stats.clear();

	rndGen.setSeed(rnd()+getpid());	
	signal(SIGPIPE, SIG_IGN); 

	rndSeed = rnd();

}

// ---------------------------------
unsigned int LSys::getTime()
{
	time_t ltime;
	time( &ltime );
	return ltime;
}

// ---------------------------------
ClientSocket *LSys::createSocket()
{
    return new LClientSocket();
}
               
typedef void *(*THREAD_PTR)(void *);

// ---------------------------------
bool	LSys::startThread(ThreadInfo *info)
{
	info->active = true;

#if 1
	pthread_t thread;
	pthread_attr_t attr;

	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

//	LOG_DEBUG("Starting thread");
	int r = pthread_create(&thread,&attr,(THREAD_PTR)info->func,info);
//	int r = pthread_create(&thread,NULL,(THREAD_PTR)info->func,info);
//	LOG_DEBUG("Starting thread done");

	if (r)
		LOG_ERROR("Error creating thread: %d",r);

	return r==0;
#endif

#if 0
	pthread_t mythread;
  
	if ( pthread_create( &mythread, NULL, (THREAD_PTR)info->func, info) ) 
	{
		LOG_ERROR("error creating thread.");
		return false;
	}

	LOG_DEBUG("Thread started OK");
//	if ( pthread_join ( mythread, NULL ) ) 
//	{
//		LOG_ERROR("error joining thread.");
//		return false;
//	}
	return true;
#endif
}
// ---------------------------------
void	LSys::sleep(int ms)
{
	::usleep(ms*1000);
}

// ---------------------------------
void LSys::appMsg(long msg, long arg)
{
	//SendMessage(mainWindow,WM_USER,(WPARAM)msg,(LPARAM)arg);
}

// ---------------------------------
void LSys::getURL(const char *url)
{
}
// ---------------------------------
void LSys::exit()
{
	::exit(0);
}

