//
//  KMReplyMessenger.m
//  BathyScaphe
//
//  Created by 堀 昌樹 on 12/04/22.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "KMReplyMessenger.h"

#import "CMRReplyMessenger.h"
#import "CMRReplyDocumentFileManager.h"
#import "AppDefaults.h"
#import "CMRThreadAttributes.h"

@implementation KMReplyMessenger
@synthesize document = _document;
@synthesize range = _range;
@synthesize index = _index;
@synthesize string = _string;


- (void)dealloc
{
	[_string release];
	[super dealloc];
}

- (void)addMessenger:(CMRReplyMessenger *)aMessenger
{
	[[NSNotificationCenter defaultCenter] addObserver:self
											 selector:@selector(replyMessengerDidFinishPosting:)
												 name:CMRReplyMessengerDidFinishPostingNotification
											   object:aMessenger];
}
- (void)removeMessenger:(CMRReplyMessenger *)aMessenger
{
	[[NSNotificationCenter defaultCenter] removeObserver:self
													name:CMRReplyMessengerDidFinishPostingNotification
												  object:aMessenger];
}
- (CMRReplyMessenger *)replyMessenger
{
	UTILAssertNotNil([self path]);
	CMRReplyMessenger *document;
	NSURL	*replyDocURL;
	NSError *error;
	
	NSDocumentController *docController = [NSDocumentController sharedDocumentController];
	CMRReplyDocumentFileManager *replyDocManager = [CMRReplyDocumentFileManager defaultManager];
	
	NSString *replyDocPath = [replyDocManager replyDocumentFilepathWithLogPath:self.document.path createIfNeeded:YES];
	replyDocURL = [NSURL fileURLWithPath:replyDocPath];
	
	document = [docController documentForURL:replyDocURL];
	if (document) return document;
	
	[replyDocManager createDocumentFileIfNeededAtPath:replyDocPath contentInfo:self.document.threadDictionary];
	document = [docController openDocumentWithContentsOfURL:replyDocURL display:YES error:&error];
	if (document) {
		[self addMessenger:document];
		return document;
	}
	if (error) {
		NSAlert *alert = [NSAlert alertWithError:error];
		[alert runModal];
	}
	// Error while creating CMRReplyMessenger instance.
	return nil;
}

- (void)replyMessengerDidFinishPosting:(NSNotification *)aNotification
{
	NSSound		*replyFinishedSound;
	NSString	*replyFinishedSoundName;
	
	[self removeMessenger:[aNotification object]];
	
	UTILAssertNotificationName(aNotification, CMRReplyMessengerDidFinishPostingNotification);
    id threadIdentifierOfMine = self.document.threadAttr.threadSignature;
    if (!threadIdentifierOfMine) {
        return;
    }
	
    NSDictionary *userInfo = [aNotification userInfo];
    id threadIdentifierOfMessenger = [userInfo objectForKey:kUserInfoPostedThreadIdentifierKey];
    
    if (![threadIdentifierOfMessenger isEqual:threadIdentifierOfMine]) {
        return; // このスレッドに対する書き込みではない
    }
	
	replyFinishedSoundName = [CMRPref replyDidFinishSound];
	if (replyFinishedSoundName && ![replyFinishedSoundName isEqualToString:@""]) {
		replyFinishedSound = [NSSound soundNamed:replyFinishedSoundName];
	} else {
		replyFinishedSound = nil;
	}
	
	[replyFinishedSound play];
	
	[self.document reloadThread:self];
}

- (void)quoteWithMessenger:(CMRReplyMessenger *)aMessenger
{
	if (NSNotFound == self.index) return;
	[aMessenger append:self.string quote:YES replyTo:self.index];
}

- (CMRReplyMessenger *)plainReply:(id)sender
{
	if (!self.document.path) return nil;
	CMRReplyMessenger *document = [self replyMessenger];
	
	if (!document) return nil;
	
	[document showWindows];
    return document;
}

- (IBAction)reply:(id)sender
{
    CMRReplyMessenger *document = [self plainReply:sender];
	if (document) {
        [self quoteWithMessenger:document];
    }
}

- (void)clearQuotation
{
	self.string = @"";
	self.index = NSNotFound;
	self.range = NSMakeRange(0, 0);
}

@end
