#include <qregexp.h>
#include <kurl.h>
#include <kapp.h>
#include "protocol.h"

SubProtocol* matchFileName(const char *str, SubProtList *list)
{
	SubProtListIterator	it(*list);
	for (;it.current();++it) if (it.current()->matchFileName(str)) break;
	return it.current();
}

KMimeExtension* Protocol::getMimeTypeFromNode(FileInfo *fi)
{
	if (fi->isDir()) {
		if (fi->isReadable()) return ExtDict->find("inode/directory");
		else return ExtDict->find("inode/directory-locked");
	}
	else if (fi->isBlock()) return ExtDict->find("inode/blockdevice");
	else if (fi->isChr()) return ExtDict->find("inode/chardevice");
	else if (fi->isFifo()) return ExtDict->find("inode/fifo");
	else if (fi->isSocket()) return ExtDict->find("inode/socket");
	else return 0;
}

KMimeExtension* Protocol::getMimeTypeFromExtension(FileInfo *fi)
{
	if (ExtDict == 0 || fi->lastExtension().isEmpty()) return 0;
	return ExtDict->find(fi->lastExtension().data());
}

KMimeExtension* Protocol::getMimeTypeFromName(FileInfo *fi)
{
	if (NameDict == 0) return 0;
	QListIterator<KMimeExtension>	it(*NameDict);
	bool	done = FALSE;
	while (it.current() && !done) {
		for (int i=0;!done && i<it.current()->nExtension();i++) {
			QRegExp		w(it.current()->extension(i),TRUE,TRUE);
			if (fi->fileName().find(w) >= 0) done = TRUE;
		}
		if (!done) ++it;
	}
	return it.current();
}

KMimeExtension* Protocol::getMimeTypeFromMagic(FileInfo *fi)
{
	if (ExtDict == 0 || Magic == 0) return 0;
	KURL	url(fi->absFilePath().data());
	const char	*c = Magic->getMimeType(url.path());
	return (c ? ExtDict->find(c) : (KMimeExtension*)0);
}

void Protocol::abort()
{
cout << "Thread ID : " << th_ID << endl;
	if (th_ID != 0) {if (pthread_cancel(th_ID) == 0) cout << "cancellation successfull" << endl;}
	else shutDown();
	th_ID = 0;
}

void Protocol::shutDown()
{}

void* thread_Interface(ProtocolCmd *cmd)
{
	pthread_cleanup_push(thread_Cleanup,cmd);
	cmd->prot->thread_protocolCmd(cmd);
	pthread_cleanup_pop(0);
	return 0;
}

void thread_Cleanup(ProtocolCmd *cmd)
{
cout << "Thread Cancel" << endl;
	cmd->prot->thread_protocolCleanup(cmd);
}

void Protocol::launchThread(struct ProtocolCmd *cmd)
{
	pthread_create(&th_ID,0,thread_Interface,(void*)cmd);
#ifdef NO_MULTI_THREAD
	pthread_join(th_ID);
#else
//	while (!cmd->done) kapp->processEvents();
	while (!cmd->done) kapp->processEvents(), usleep(50000);
#endif
	kapp->processEvents();
}
