// 
//  BSThreadListItemObject.m
//  BathyScaphe
//
//  Created by Hori,Masaki on 10/10/17.
//  Copyright 2010 masakih. All rights reserved.
//

#import "BSThreadListItemObject.h"

#import "BSThreadInformationObject.h"

#include <objc/runtime.h>

@implementation BSThreadListItemObject 

@dynamic index;
@dynamic thread;

static NSMethodSignature *sSig = nil;


- (NSNumber *)threadnumber
{
	return self.index;
}
- (NSNumber *)threadNumber
{
	return self.index;
}



- (NSMethodSignature *)sig
{
	if(sSig) return sSig;
	
	Method method = class_getInstanceMethod([self class], @selector(returnNil));
	const char *encode = method_getTypeEncoding(method);
	sSig = [[NSMethodSignature signatureWithObjCTypes:encode] retain];
	
	return sSig;
}
- (id)returnNil
{
	return nil;
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector;
{
	if([self.thread respondsToSelector:aSelector]) {
		return [self.thread methodSignatureForSelector:aSelector];
	}
	if(!self.thread) {
//		NSLog(@"%s thread is nil", __PRETTY_FUNCTION__);
		NSString *selName = NSStringFromSelector(aSelector);
		if(![selName hasSuffix:@":"]) {
			return [self sig];
		}
	}
	
	return [super methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
	SEL selector = [anInvocation selector];
	if([self.thread respondsToSelector:selector]) {
		[anInvocation invokeWithTarget:self.thread];
		return;
	}
	
	NSMethodSignature *sig = [anInvocation methodSignature];
	if(sig == [self sig]) {
		[anInvocation setSelector:@selector(returnNil)];
		[anInvocation invokeWithTarget:self];
		return;
	}
}

- (id)valueForUndefinedKey:(NSString *)key
{
	id result = nil;
	
	@try {
		result = [self.thread valueForKey:key];
	}
	@catch (id ex) {
		NSLog(@"%@", ex);
		@throw;
	}
	
	return result;
}
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
	@try {
		[self.thread setValue:value forKey:key];
	}
	@catch (id ex) {
		NSLog(@"%@", ex);
		@throw;
	}
}
@end
