//
//  KMDocument+LoadLogWindow.m
//  BathyScaphe
//
//  Created by 堀 昌樹 on 12/05/11.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "KMDocument+LoadLogWindow.h"
#import "CMRThreadMessageBufferReader.h"
#import "CMRThreadComposingTask.h"
#import "CMRAttributedMessageComposer.h"
#import "CMRThreadMessageBuffer.h"

#include <objc/runtime.h>

@implementation KMDocument (LoadLogWindow)
- (NSString *)windowNibName
{
	return NSStringFromClass([self class]);
}

- (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)typeName error:(NSError **)outError
{
	NSLog(@"Use category method.");
		
	[self loadContentOfFile:[url path]];
	[self performSelector:@selector(composeThread:) withObject:nil afterDelay:0.0];
	return YES;
}

- (void)awakeFromNib
{
	self.composedMessages = [NSMutableArray array];
	self.logView.delegate = self;
	self.logView.datasource = self;
}


- (KMLogView *)logView
{
	return objc_getAssociatedObject(self, @"logView");
}
- (void)setLogView:(KMLogView *)logView
{
	objc_setAssociatedObject(self, @"logView", logView, OBJC_ASSOCIATION_ASSIGN);
}
- (NSMutableArray *)composedMessages
{
	return objc_getAssociatedObject(self, @"composedMessages");
}
- (void)setComposedMessages:(NSMutableArray *)composedMessages
{
	objc_setAssociatedObject(self, @"composedMessages", composedMessages, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


- (void)composeThread:(id)dummy
{
	CMRThreadMessageBufferReader *reader = [CMRThreadMessageBufferReader readerWithContents:self.messageBuffer];
	[reader setNextMessageIndex:[self.composedMessages count]];

	
	CMRThreadMessageBuffer			*buffer_;
	NSMutableAttributedString		*textBuffer_;
	CMRAttributedMessageComposer	*composer_;
		
	buffer_ = [[[CMRThreadMessageBuffer alloc] init] autorelease];
	UTILAssertNotNil(reader);
	
	[reader composeWithComposer:buffer_];
		
	// compose text storage
	composer_ = [[CMRAttributedMessageComposer alloc] init];
	textBuffer_ = [[NSMutableAttributedString alloc] init];
	[composer_ setContentsStorage:textBuffer_];
	
    NSArray *messages = [buffer_ messages];
	
    for (CMRThreadMessage *message in messages) {
		[textBuffer_ deleteCharactersInRange:NSMakeRange(0, [textBuffer_ length])];
		[composer_ composeThreadMessage:message];
		id copyStr = [textBuffer_ copy];
		[self.composedMessages addObject:copyStr];
		[copyStr release];
	}
	
	[textBuffer_ release];
	[composer_ release];
	
	[self.logView reloadData];
}

- (NSInteger)numberOfRowsInLogView:(KMLogView *)logView
{
	return [self.composedMessages count];
}

- (NSAttributedString *)logView:(KMLogView *)logView attributedStringForRow:(NSInteger)row
{
	return [self.composedMessages objectAtIndex:row];
}


- (void)test01:(id)sender
{
	[NSApp sendAction:@selector(showRanges:) to:nil from:self];
}

@end
