#import "netFixerAppDelegate.h"
#import <WebKit/WebKit.h>
#import "webImpressor.h"

@implementation netFixerAppDelegate
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification{
    /* Setting base extension */
    extension = @".png";
    
    /* Setting delegate for event GetUrl when someone click on protocol netfixer: */
    [[NSAppleEventManager sharedAppleEventManager] setEventHandler:self andSelector:@selector(getUrl:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL];
    
    /* Making fake window */
    NSRect rect = NSMakeRect(-16000,-16000,100,100);
    NSWindow *win = [NSWindow alloc];
    [win initWithContentRect:rect styleMask:NSBorderlessWindowMask backing:2 defer:0];

    /* Making webView */
    wb = [[WebView alloc]initWithFrame:rect];
    [[[wb mainFrame] frameView] setAllowsScrolling:NO];
    
    /* Adding webView to fake window */
    [win setContentView:wb];

    /* Setting delegar for loading frame */
    loadDelegate = [[webImpressor alloc]init];
    [wb setFrameLoadDelegate:loadDelegate];
    
    /*Passing the well for stopping it when the impressor has finished*/
    [loadDelegate setProgWell:progWell];
    
}

- (void)awakeFromNib{
	[self loadPref];
    /* Adding toolbar to the windows */
    [self addToolbar:mainWin];

}

- (void) loadUrl: (NSString *)url{
    NSMutableString* urlmod = [NSMutableString stringWithString:url];
    [urlmod replaceOccurrencesOfString:@" " withString:@"" options:nil range:NSMakeRange(0, [url length])];

    /* load url and save image ;) */
    [[wb mainFrame]loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlmod]]];
}

//- (void) shotIt{
- (IBAction)shotIt:(id)sender{
    /* Getting url to be shooted*/
    NSString *url = [adrField stringValue];
    
    if([url isEqualToString:@""] == 1){
        /* Error if someone try to shot without fill url field*/
        NSAlert *a = [NSAlert alertWithMessageText:@"You must provide a url to shot!" 
                 defaultButton:@"ok" 
                 alternateButton:nil 
                 otherButton:nil 
                 informativeTextWithFormat:@""];
        [a runModal];
        return;
    }
    
    if([url hasPrefix:@"http://"] != 1){
        
        url = [@"http://" stringByAppendingString:url];
    }
    
    /* Filename creation */
    NSMutableString* filename = [NSMutableString stringWithString:[url substringFromIndex:7]];
    [filename replaceOccurrencesOfString:@"/" withString:@"." options:nil range:NSMakeRange(0, [url length]-7)];
    
    /* Base name for the shot */
    NSString* basename = [filename stringByAppendingString:extension];
    
    /* NSSave panel for output */
    NSSavePanel* sp = [NSSavePanel savePanel];
    [sp setCanCreateDirectories:1];
    [sp setMessage:@"Where to save the shotted site?"];
    int res = [sp runModalForDirectory:@"~/" file: basename];
    if (res == 1){
        
        /*Starting well*/
        [progWell startAnimation:self];    
            
        /* Setting output filename */
        [loadDelegate setFileName:[sp filename]];
        
        /* Loading url in wb*/
        [self loadUrl:url];
    }
    /*End of save panel*/
}

- (void)changeTab:(id)sender{
    if([[sender label]isEqualToString:@"Shoot it!"]){
        [tabView selectTabViewItemAtIndex:0];

    }
    else if ([[sender label]isEqualToString:@"Settings!"]){
        [tabView selectTabViewItemAtIndex:1];
    }

}

- (IBAction)setFormat:(id)sender{
    NSString* format = [sender titleOfSelectedItem];
    if([format isEqualToString:@"png"]){[loadDelegate setFormat: NSPNGFileType];extension = @".png";}
    else if([format isEqualToString:@"jpg"]){[loadDelegate setFormat: NSJPEGFileType]; extension = @".jpg";}
    else if([format isEqualToString:@"tiff"]){[loadDelegate setFormat: NSTIFFFileType];extension = @".tif";}
    else if([format isEqualToString:@"gif"]){[loadDelegate setFormat: NSGIFFileType];extension = @".gif";}
    else if([format isEqualToString:@"bmp"]){[loadDelegate setFormat: NSBMPFileType];extension = @".bmp";}
}

- (IBAction)setSize:(id)sender{
    NSString* size =  [[sender selectedCell]title];
    NSRect rect;
    NSSize csize;
    if([size isEqualToString:@"640x480"]){
        rect = NSMakeRect(0,0,640,480); 
        csize = NSMakeSize(640,480);
        }
    else if([size isEqualToString:@"800x600"]){
        rect = NSMakeRect(0,0,800,600); 
        csize = NSMakeSize(800,600);
    }
    else if([size isEqualToString:@"1024x768"]){
        rect = NSMakeRect(0,0,1024,768); 
        csize = NSMakeSize(1024,768);
    }
    [loadDelegate setCanvas:rect canvasSize:csize];
}

- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag
{
    [mainWin makeKeyAndOrderFront:self];
    return 1;
}
- (void)applicationWillTerminate:(NSNotification *)aNotification
{
	[self savePref];
}

#pragma mark Preferences

- (void) savePref{
	int size;
	
	int i;
	for (i=0; i<[sizeMatrix numberOfColumns]; i++){
		if([[sizeMatrix cellAtRow:0 column:i]state]==YES)
			size = i;
	}

	int output = [outputPopup indexOfSelectedItem];

	[[NSUserDefaults standardUserDefaults] setInteger:size forKey:@"canvasSize"];
	[[NSUserDefaults standardUserDefaults] setInteger:output forKey:@"outputType"];
	//NSLog(@"Save: size -> %d \n output -> %d", size, output);
}

- (void) loadPref{
	int size = [[NSUserDefaults standardUserDefaults] integerForKey:@"canvasSize"];
	int output = [[NSUserDefaults standardUserDefaults] integerForKey:@"outputType"];
	//NSLog(@"Load: size -> %d \n output -> %d", size, output);

	int i;
	for (i=0; i<[sizeMatrix numberOfColumns]; i++)
		if (i == size)
			[[sizeMatrix cellAtRow:0 column:i] setState:YES];
		else
			[[sizeMatrix cellAtRow:0 column:i] setState:NO];

	[outputPopup selectItemAtIndex:output];
}


#pragma mark Toolbar settings

#define        TB_shot        @"tb_shotItem"
#define        TB_id          @"tb_toolbar"
#define        TB_pref        @"tb_prefItem"
 
- (NSArray *) toolbarDefaultItemIdentifiers: (NSToolbar *) toolbar {
    /* Item default in the toolbar */    
    return [NSArray arrayWithObjects:   
        NSToolbarFlexibleSpaceItemIdentifier,    // flexible space 
        TB_shot,             // Shot
        TB_pref,
        NSToolbarFlexibleSpaceItemIdentifier,    // flexible space
        //NSToolbarCustomizeToolbarItemIdentifier,// customize item
        nil]; 
}

- (NSArray *) toolbarAllowedItemIdentifiers: (NSToolbar *) toolbar{
    /* item allowed in the toolbar */
    return [NSArray arrayWithObjects:
        TB_shot,
        NSToolbarFlexibleSpaceItemIdentifier,     // flexible space
        TB_pref,
        NSToolbarCustomizeToolbarItemIdentifier,// customize item
        nil]; 
}

- (NSToolbarItem *) toolbar: (NSToolbar *)toolbar 
    itemForItemIdentifier: (NSString *) itemIdent
    willBeInsertedIntoToolbar:(BOOL) willBeInserted{
        
        NSToolbarItem *toolbarItem = [[[NSToolbarItem alloc] initWithItemIdentifier: itemIdent] autorelease]; 
    if ([itemIdent isEqual: TB_shot]){
        /* Shot icon definition */
        [toolbarItem setLabel: @"Shoot it!"];
        [toolbarItem setPaletteLabel: @"Shoot it!"];
        [toolbarItem setToolTip: @"Shoot a selected site"];
        [toolbarItem setImage: [NSImage imageNamed: @"shot.png"]];
        [toolbarItem setTarget: self];
        [toolbarItem setAction: @selector(changeTab:)];
        return toolbarItem;
        }
    if ([itemIdent isEqual: TB_pref]){
        /* Shot icon definition */
        [toolbarItem setLabel: @"Settings!"];
        [toolbarItem setPaletteLabel: @"Settings!"];
        [toolbarItem setToolTip: @"Setting for Nexfixer"];
        [toolbarItem setImage: [NSImage imageNamed: @"pref.png"]];
        [toolbarItem setTarget: self];
        [toolbarItem setAction: NSSelectorFromString(@"changeTab:")];
        return toolbarItem;
        }
        
        return nil;
    }
    

- (void) addToolbar: (NSWindow *) win{
    // costruisco la nuova istanza della toolbar
    // la faccio autorelease perche' sara' poi ritenuta dalla finestra
    NSToolbar *toolbar = [[[NSToolbar alloc] initWithIdentifier: TB_id] autorelease];

    // imposto le proprieta' di base della toolbar
    // permetto che l'utente la modifichi
    [toolbar setAllowsUserCustomization: YES];
    // lascio che conservi lo stato tra successivi lanci
    [toolbar setAutosavesConfiguration: YES];
    // dico che mostri solo le icone
    //[toolbar setDisplayMode: NSToolbarDisplayModeIconOnly];
    [toolbar setDisplayMode: NSToolbarDisplayModeIconAndLabel];

    // dico che il delegato della toolbar e' il documento stesso
    [toolbar setDelegate: self];
    // attacco la toolbar alla finestra
    [ win setToolbar: toolbar ];
}

#pragma mark Url delegate handler

- (void)getUrl:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
	[mainWin makeKeyAndOrderFront:self];
    /* This function respond to a GURL event, so after we catch the url we can do all what we want */
	NSString *url = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
	// now you can create an NSURL and grab the necessary parts for example
    url = [url substringFromIndex:9];
    [adrField setStringValue:url];
    //NSLog(url);
}

/* Goodly features, netfixer bookmarklet
javascript:%20var%20baseUrl%20=%20'netfixer:';%20var%20url=baseUrl;
var%20currentUrl=document.location.href;url=url%20+%20currentUrl;%20location.href=url;
*/
@end
