/*
SRDocumentController.m

Author: Makoto Kinoshita

Copyright 2004-2006 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "SRBrowserDocument.h"
#import "SRBrowserController.h"
#import "SRDocumentController.h"

#import "SRDefaultKeys.h"
#import "SRPrefDefaultKeys.h"

@implementation SRDocumentController

- (id)openDocumentWithContentsOfFile:(NSString*)fileName 
        display:(BOOL)flag
{
    // Get documents
    NSArray*    documents;
    documents = [self documents];
    
    // Open with first empty document
    if ([documents count] > 0) {
        NSEnumerator*           enumerator;
        id                      document;
        SRBrowserDocument*      emptyDocument = nil;
        SRBrowserController*    emptyBrowserController = nil;
        
        // Find empty document and document with same file
        enumerator = [documents objectEnumerator];
        while (document = [enumerator nextObject]) {
            if (![document isKindOfClass:[SRBrowserDocument class]]) {
                continue;
            }
            
            // Get window controller
            SRBrowserController*    browserController;
            browserController = [(SRBrowserDocument*)document browserController];
            
            // Get file name
            if ([fileName isEqualToString:[document fileName]]) {
                // Reload this file
                [document readFromFile:fileName ofType:SRHTMLDocumentType];
                [[browserController window] makeKeyAndOrderFront:self];
                return document;
            }
            
            // Check web data source of selected web view
            if (![[[[browserController selectedPageController] webView] mainFrame] dataSource]) {
// Temp
if ([document valueForKey:@"initialFileName"]) {
    // Not empty document
    continue;
}
                // This is empty document
                if (!emptyDocument) {
                    emptyDocument = document;
                    emptyBrowserController = browserController;
                }
            }
        }
        
        // Open with empty document
        if (emptyDocument) {
// Temp
[emptyDocument setValue:fileName forKey:@"initialFileName"];
            [emptyDocument setFileName:fileName];
            [emptyDocument readFromFile:fileName ofType:SRHTMLDocumentType];
            [[emptyBrowserController window] makeKeyAndOrderFront:self];
            return emptyDocument;
        }
    }
    
    return [super openDocumentWithContentsOfFile:fileName display:flag];
}

- (id)openDocumentWithContentsOfURL:(NSURL*)URL 
        display:(BOOL)flag 
        error:(NSError**)error
{
    // Get defaults
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    BOOL    openURLUseTab, selectTab;
    selectTab = [defaults boolForKey:SRTabSelectNewTabs];
    openURLUseTab = [defaults boolForKey:SRTabOpenURLUseTab];
    
    // Get documents
    NSArray*    documents;
    documents = [self documents];
    
    // Open with first empty document
    if ([documents count] > 0) {
        NSEnumerator*           enumerator;
        id                      document;
        SRBrowserDocument*      emptyDocument = nil;
        SRBrowserController*    emptyBrowserController = nil;
        
        // Find empty document and document with same file
        enumerator = [documents objectEnumerator];
        while (document = [enumerator nextObject]) {
            if (![document isKindOfClass:[SRBrowserDocument class]]) {
                continue;
            }
            
            // Get window controller
            SRBrowserController*    browserController;
            browserController = [(SRBrowserDocument*)document browserController];
            
            // Open with tab
            if (openURLUseTab) {
                // For empty document
                if (![[[[browserController selectedPageController] webView] mainFrame] dataSource]) {
                    [document readFromURL:URL ofType:SRHTMLDocumentType inNewTab:NO select:NO];
                }
                else {
                    [document readFromURL:URL ofType:SRHTMLDocumentType inNewTab:YES select:selectTab];
                }
                return document;
            }
            
            // Check web data source of selected web view
            if (![[[[browserController selectedPageController] webView] mainFrame] dataSource]) {
                // This is empty document
                if (!emptyDocument) {
                    emptyDocument = document;
                    emptyBrowserController = browserController;
                    break;
                }
            }
        }
        
        // Open with empty document
        if (emptyDocument) {
            [emptyDocument readFromURL:URL ofType:SRHTMLDocumentType];
            [[emptyBrowserController window] makeKeyAndOrderFront:self];
            return emptyDocument;
        }
    }

    // Create document
    id  document;
    [self setShouldCreateUI:YES];
    document = [self openUntitledDocumentOfType:SRHTMLDocumentType display:flag];
    [document readFromURL:URL ofType:SRHTMLDocumentType];
    return document;
}

- (NSArray*)fileExtensionsFromType:(NSString*)typeName
{
    // Get from super
    NSArray*    types;
    types = [super fileExtensionsFromType:typeName];
    if (types && [types count] > 0) {
        return types;
    }
    
    // Since type name must be MIME name, retuen it as is
    return [NSArray arrayWithObject:typeName];
}

- (NSString*)defaultType
{
    return SRHTMLDocumentType;
}

@end
