/* 
   NSThread.m

   Copyright (C) 1995, 1996 Ovidiu Predescu and Mircea Oancea.
   All rights reserved.

   Author: Mircea Oancea <mircea@jupiter.elcom.pub.ro>

   This file is part of libFoundation.

   Permission to use, copy, modify, and distribute this software and its
   documentation for any purpose and without fee is hereby granted, provided
   that the above copyright notice appear in all copies and that both that
   copyright notice and this permission notice appear in supporting
   documentation.

   We disclaim all warranties with regard to this software, including all
   implied warranties of merchantability and fitness, in no event shall
   we be liable for any special, indirect or consequential damages or any
   damages whatsoever resulting from loss of use, data or profits, whether in
   an action of contract, negligence or other tortious action, arising out of
   or in connection with the use or performance of this software.
*/

#include <Foundation/common.h>
#include <Foundation/NSAutoreleasePool.h>
#include <Foundation/NSDictionary.h>
#include <Foundation/NSString.h>
#include <Foundation/NSNotification.h>
#include <Foundation/NSUtilities.h>
#include <Foundation/NSObjCRuntime.h>
#include <Foundation/NSThread.h>
#include <Foundation/NSLock.h>

#include <Foundation/NSException.h>
#include <Foundation/exceptions/GeneralExceptions.h>

/*
    NSAutoreleasePool must be changed to return a default pool from 
    the current thread autorelease stack and to operate on that stack
    when pools are allocated and deallocated. The overhead is one more
    method call in +[NSAutoreleasePool defaultPool] to 
    +[NSThread currentThread].

    NSExceptions && exception handlers must be changed to use current
    thread top-level handler instead of internal static variable. The
    overhead is not important since handler are not pushed/extracted
    too often.
 */

/* NSThread notifications */

NSString* NSWillBecomeMultiThreadedNotification = 
	@"NSWillBecomeMultiThreadedNotification";
NSString* NSThreadWillExitNotification =
	@"NSThreadWillExitNotification";

/* Global thread variables */

static BOOL isMultiThreaded = NO;
static NSThread* mainThread = nil;

NSLock* libFoundationLock = nil;

@implementation NSThread

/*
 * Instance Methods
 */

- initWithTarget:(id)aTarget selector:(SEL)aSelector argument:(id)anArgument
{
    // Not yet running
    isRunning = NO;
    // Set running parameters
    target = aTarget;
    selector = aSelector;
    arg = anArgument;
    // Autorelease pool is nil
    autoreleaseStack = nil;
    // No exception handler
    exceptionStack = NULL;
    // Thread dictionary
    threadDictionary = [NSMutableDictionary new];
    
    return self;
}

- (void)run
{
    id pool;
    
    // Set current thread data
    objc_thread_set_data(self);
    // Make thread-top-level autorelease
    pool = [[NSAutoreleasePool alloc] init];
    // Run 
    [target perform:selector withObject:arg];
    // pool cleanup
    [pool release];
}

- (void)exit
{
    // Clear autorelease for current thread
    while (autoreleaseStack)
	[autoreleaseStack release];
    objc_thread_exit();
}

- (NSMutableDictionary*)threadDictionary
{
    return threadDictionary;
}

- (void)dealloc
{
    if (isRunning)
	THROW([[InvalidUseOfMethodException alloc] initWithFormat:
	    @"cannot deallocate NSThread for running thread"]);
    [threadDictionary release];
    [super dealloc];
}

- (NSAutoreleasePool*)threadDefaultAutoreleasePool
{
    return autoreleaseStack;
}

- (void)setThreadDefaultAutoreleasePool:(NSAutoreleasePool*)pool
{
    autoreleaseStack = pool;
}

- (void*)threadDefaultExceptionHandler
{
    return exceptionStack;
}

- (void)setThreadDefaultExceptionHandler:(void*)handler
{
    exceptionStack = handler;
}

/*
 * Class Methods
 */

+ (void)initialize
{
    // We are still in non-multithread state
    if (!mainThread) {
	mainThread = [NSThread alloc];
	mainThread->threadDictionary = [NSMutableDictionary new];
	mainThread->autoreleaseStack = nil;
	mainThread->exceptionStack = NULL;
	objc_thread_set_data(mainThread);
    }
}

static void nsThreadStartThread(id thread)
{
    [thread run];
    [thread exit];
    [thread release];
}

+ (void)detachNewThreadSelector:(SEL)aSelector 
  toTarget:(id)aTarget withObject:(id)anArgument
{
    id thread = [[self alloc] 
	initWithTarget:aTarget selector:aSelector argument:anArgument];
    
    if (!isMultiThreaded) {
	[NSAutoreleasePool taskNowMultiThreaded:nil];
	[NSException taskNowMultiThreaded:nil];
	[[NSNotificationCenter defaultCenter]
	    postNotificationName:NSWillBecomeMultiThreadedNotification
	    object:nil userInfo:nil];
	isMultiThreaded = YES;
    }
    
    objc_thread_create((void(*)(void*arg))nsThreadStartThread, thread);
}

+ (NSThread*)currentThread
{
    return isMultiThreaded ? (NSThread*)objc_thread_get_data() : mainThread;
}

+ (void)exit
{
    [[NSNotificationCenter defaultCenter]
	postNotificationName:NSThreadWillExitNotification
	object:self userInfo:nil];
    [[self currentThread] exit];
}

+ (BOOL)isMultiThreaded
{
    return isMultiThreaded;
}

+ (void)sleepUntilDate:(NSDate*)aDate
{
    // TODO
    [self notImplemented:_cmd];
}

@end /* NSThread */
