//
//  AppDelegate.m
//  SimpleHTMLEditor
//
//  Created by 西田　耀 on 13/04/13.
//  Copyright (c) 2013年 CHNOSProject. All rights reserved.
//

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)notification
{
    //エディタフォント設定
    [sourceEditor setFont:[NSFont fontWithName:@"Source Code Pro" size:14]];
    //自動改行無効
    [[sourceEditor textContainer] setContainerSize:NSMakeSize(FLT_MAX, FLT_MAX)];
    [[sourceEditor textContainer] setWidthTracksTextView:NO];
    [sourceEditor setHorizontallyResizable:YES];
}

- (IBAction)addressBarURIChanged:(id)sender {
    mainWebView.mainFrameURL = addressBar.stringValue;
}

- (IBAction)openCurrentURIForEdit:(id)sender {
    if([sourceEditor.string isEqualToString:@""]){
        [self openCurrentURIForEdit_ReadURI];
    } else{
        NSBeginAlertSheet(@"SimpleHTMLEditor", @"No", @"Yes", nil, mainWindow, self.self, @selector(openCurrentURIForEdit_sheetClosed:returnCode:contextInfo:), nil, nil, @"Do you want to discard changes?");
    }
}

- (void)openCurrentURIForEdit_sheetClosed:(id)sheet returnCode:(int)returnCode contextInfo:(id)contextInfo
{
    switch (returnCode) {
        case NSAlertDefaultReturn:
            
            break;
            
        case NSAlertAlternateReturn:
            [self openCurrentURIForEdit_ReadURI];
            break;
    }
}

- (void)openCurrentURIForEdit_ReadURI
{
    editingFileURILabel.stringValue = mainWebView.mainFrameURL;
    
    //sourceEditor.string = [mainWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
    sourceEditor.string = [NSString stringWithContentsOfURL:[NSURL URLWithString:mainWebView.mainFrameURL] encoding:NSUTF8StringEncoding error:nil];
}

- (void)webView:(WebView *)sender didStartProvisionalLoadForFrame:(WebFrame *)frame
{
    if(frame == sender.mainFrame){
        addressBar.stringValue = sender.mainFrameURL;
    }
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{
    return YES;
}

- (void)saveEditingDocumentForFile:(id)sender
{
    NSSavePanel *savePanel;
    NSArray *allowedFileType;
    NSInteger pressedButton;
    NSURL *path;
    NSError *error;
    
    if([[editingFileURILabel stringValue] isEqualToString:@""] || sender == MenuItem_SaveAs){
        //ファイル名をユーザーに入力させる
        savePanel = [NSSavePanel savePanel];
        allowedFileType = [NSArray arrayWithObjects:@"htm", @"html", nil];
        [savePanel setAllowedFileTypes:allowedFileType];
        
        pressedButton = [savePanel runModal];
        
        switch(pressedButton){
            case NSOKButton:
                path = [savePanel URL];
                error = nil;
                [[sourceEditor string] writeToURL:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
                if(error != nil){
                    NSRunAlertPanel(@"SimpleHTMLEditor-Error-", [error localizedDescription], @"OK", nil, nil);
                } else{
                    [editingFileURILabel setStringValue:[path path]];
                }
                
                break;
            case NSCancelButton:
                
                break;
        };
    } else{
        //開いたURIに保存する。
        path = [NSURL fileURLWithPath:[[editingFileURILabel stringValue] stringByReplacingOccurrencesOfString:@"file://" withString:@""]];
        
        error = nil;
        [[sourceEditor string] writeToURL:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
        if(error != nil){
            NSRunAlertPanel(@"SimpleHTMLEditor-Error-", [error localizedDescription], @"OK", nil, nil);
        }
        
        
    }
}

- (IBAction)revertToSaved:(id)sender
{
    NSBeginAlertSheet(@"SimpleHTMLEditor", @"No", @"Yes", nil, mainWindow, self.self, @selector(revertToSaved_sheetClosed: returnCode:contextInfo:), nil, nil, @"Do you want to revert to saved?");
}

- (void)revertToSaved_sheetClosed:(id)sheet returnCode:(int)returnCode contextInfo:(id)contextInfo
{
    switch (returnCode) {
        case NSAlertDefaultReturn:
            
            break;
            
        case NSAlertAlternateReturn:
            sourceEditor.string = [mainWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
            break;
    }
}

- (void)webView:(WebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame
{
    NSRunAlertPanel(@"alert", message, @"OK", nil, nil);
}

- (BOOL)webView:(WebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame
{
    NSInteger result = NSRunAlertPanel(@"confirm", message, @"OK", @"Cancel", nil);
    if (result == NSAlertDefaultReturn) {
        return YES;
    }
    return NO;
}

- (void) webView:(WebView*)webView addMessageToConsole:(NSDictionary*)message
{
    NSLog(@"%@", message);
    logViewer.string = [logViewer.string stringByAppendingFormat:@"%@\n", message];
}

- (void) clearLogView:(id)sender
{
    logViewer.string = @"";
}

@end
