//
//  VersionReporter.m
//  VersionReporter
//
//  Created by andrew on 10/8/10.
//  Copyright 2010 Machine Perception Technologies. All rights reserved.
//

#import "VersionReporter.h"

//#import "MPT_Demo.h"

@implementation VersionReporter
- (id)initWithBundle:(NSBundle *)_bundle
{
	if( self = [super initWithBundle:_bundle] )
	{
		if( ![NSBundle loadNibNamed:@"ReporterPref" owner:self] )
			NSLog( @"Unable to load pref pane for VersionReporter plugin." );
		
	}
	return self;
}

- (void)awakeFromNib
{

}

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

// It's not OK to copy this plugin, so return nil.
- (id)copyWithZone:(NSZone *)zone
{
	return nil;
}

- (NSString *)pluginString {
    return [[pluginString retain] autorelease];
}

- (void)setPluginString:(NSString *)value {
    if (pluginString != value) {
        [pluginString release];
        pluginString = [value copy];
    }
}

- (NSString *)step
{
	return MPT_PluginStep_NoStep;
}

- (NSString *)localizedName
{
	return NSLocalizedStringFromTableInBundle(@"Version Reporter", nil, [NSBundle bundleForClass:[self class]], @"");
}

- (NSString *)internalName
{
	return @"versionreporter";
}

- (NSView *)prefPane
{
	return prefView;
}

- (BOOL)enabled
{
    return NO;
}

- (void)pluginsFinishedLoading:(NSArray *)plugins
{
	NSMutableString *pstr = [NSMutableString string];
	NSEnumerator *pluginEnum = [plugins objectEnumerator];
	id<MPT_PluginProtocol> plugin;
	while( plugin = [pluginEnum nextObject] )
	{
#ifdef DEBUG
		[pstr appendFormat:@"%@\t%@\t%@\t%@\t%@\n", [plugin localizedName], [plugin pluginID], [plugin version], ([plugin enabled]?@"Enabled":@"Disabled"), ([plugin display]?@"Display":@"NoDisplay")];
#else
		[pstr appendFormat:@"%@\t%@\t%@\n", [plugin localizedName], [plugin pluginID], [plugin version]];
#endif
	}
	[self setPluginString:pstr];
}

- (NSString *)generateVersionReport
{
	NSBundle *certBundle = [NSBundle bundleWithIdentifier:@"edu.ucsd.mplab.CERTFramework"];
	NSString *mptVersion = [certBundle objectForInfoDictionaryKey:@"MPTVersion"];
	NSString *certVersion = [certBundle objectForInfoDictionaryKey:@"CERTVersion"];
	NSString *demoString = @"";
		
	if( [[self delegate] isEvaluation] )
		demoString = @" Evaluation";
	else if( [[self delegate] isLicensed] )
		demoString = @" Licensed";
	else if( [[self delegate] isInternal] )
		demoString = @" Internal";

    NSMutableString *res = [NSMutableString stringWithFormat:@"build %@::%@%@\n", mptVersion, certVersion, demoString];
    [res appendString:@"Plugins (Name, ID, version):\n"];
	[res appendString:pluginString];
    return res;
}

-(IBAction)saveToFile:(id)sender
{
	NSWindow *modalWindow = nil;
    NSSavePanel *savePanel = [NSSavePanel savePanel];
    [savePanel setPrompt:@"Save"];
    [savePanel setTitle:@"Save Version Report"];
	[savePanel setExtensionHidden:NO];
	
    NSString *filename = @"AFECT Version Report";
    NSString *ext = @"txt";
	[savePanel setAllowedFileTypes:nil];
	[savePanel setAllowedFileTypes:[NSArray arrayWithObject:ext]];
	[savePanel setRequiredFileType:ext];
	[savePanel setExtensionHidden:NO];
	
	if( [sender isKindOfClass:[NSWindow class]] )
	{
		modalWindow = sender;
	}
	else {
		modalWindow = [prefView window];
	}

    [savePanel beginSheetForDirectory:nil
                                 file:filename
                       modalForWindow:modalWindow
                        modalDelegate:self
                       didEndSelector:@selector(savePanelDidEnd:returnCode:contextInfo:)
                          contextInfo:nil];
}

- (void)savePanelDidEnd:(NSSavePanel *)panel returnCode:(int)returnCode  contextInfo:(void  *)contextInfo
{
	if( returnCode == NSOKButton )
	{
        NSString *path = [panel filename];
        if( [path length] > 0 )
        {
			NSString *rep = [self generateVersionReport];
			NSError *error = nil;
			if( ![rep writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error] )
				[NSAlert alertWithError:error];
        }
	}
}

-(IBAction)sendToMail:(id)sender
{
 	NSString *rep = [self generateVersionReport];
//	NSString *urlString = [NSString stringWithFormat:@"mailto:support@mpt4u.com?subject=AFECT Version Report&body=%@", rep];
	// Blank destination because I don't know what, if anything, should be the default.
	NSString *urlString = [NSString stringWithFormat:@"mailto:?subject=AFECT Version Report&body=%@", rep];
	urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	NSURL *url = [NSURL URLWithString:urlString];
	
    if( !url || ![[NSWorkspace sharedWorkspace] openURL:url] )
		[NSAlert alertWithMessageText:@"Unable to create a message in your default email application"
						defaultButton:@"Ok" alternateButton:@"" otherButton:@""
			informativeTextWithFormat:@"Try saving a Version Report to a file and mailing it manually."];
}

@end
