/*
SRDocumentController.m

Author: Makoto Kinoshita

Copyright 2004 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 "SRDocumentController.h"
#import "SRMainDocument.h"
#import "SRMainWindowController.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;
        SRMainDocument*         emptyDocument = nil;
        SRMainWindowController* emptyWindowController = nil;
        
        // Find empty document and document with same file
        enumerator = [documents objectEnumerator];
        while (document = [enumerator nextObject]) {
            if (![document isKindOfClass:[SRMainDocument class]]) {
                continue;
            }
            
            // Get window controller
            SRMainWindowController* windowController;
            windowController = [(SRMainDocument*)document mainWindowController];
            
            // Get file name
            if ([fileName isEqualToString:[document fileName]]) {
                // Reload this file
                [document readFromFile:fileName ofType:SRHTMLDocumentType];
                [[windowController window] makeKeyAndOrderFront:self];
                return document;
            }
            
            // Check web data source of selected web view
            if (![[[windowController selectedWebView] mainFrame] dataSource]) {
// Temp
if ([document valueForKey:@"initialFileName"]) {
    // Not empty document
    continue;
}
                // This is empty document
                if (!emptyDocument) {
                    emptyDocument = document;
                    emptyWindowController = windowController;
                }
            }
        }
        
        // Open with empty document
        if (emptyDocument) {
// Temp
[emptyDocument setValue:fileName forKey:@"initialFileName"];
            [emptyDocument setFileName:fileName];
            [emptyDocument readFromFile:fileName ofType:SRHTMLDocumentType];
            [[emptyWindowController window] makeKeyAndOrderFront:self];
            return emptyDocument;
        }
    }
    
    return [super openDocumentWithContentsOfFile:fileName display:flag];
}

- (id)openDocumentWithContentsOfURL:(NSURL*)URL 
        display:(BOOL)flag 
        error:(NSError**)error
{
    // Get documents
    NSArray*    documents;
    documents = [self documents];
    
    // Open with first empty document
    if ([documents count] > 0) {
        NSEnumerator*           enumerator;
        id                      document;
        SRMainDocument*         emptyDocument = nil;
        SRMainWindowController* emptyWindowController = nil;
        
        // Find empty document and document with same file
        enumerator = [documents objectEnumerator];
        while (document = [enumerator nextObject]) {
            if (![document isKindOfClass:[SRMainDocument class]]) {
                continue;
            }
            
            // Get window controller
            SRMainWindowController* windowController;
            windowController = [(SRMainDocument*)document mainWindowController];
            
            // Check web data source of selected web view
            if (![[[windowController selectedWebView] mainFrame] dataSource]) {
                // This is empty document
                if (!emptyDocument) {
                    emptyDocument = document;
                    emptyWindowController = windowController;
                    break;
                }
            }
        }
        
        // Open with empty document
        if (emptyDocument) {
            [emptyDocument readFromURL:URL ofType:SRHTMLDocumentType];
            [[emptyWindowController 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

@implementation NSDocumentController (MIMEType)

- (NSString*)typeFromMIMEType:(NSString*)MIMEType
{
    // Get info dictionary
    NSDictionary*   infoDict;
    infoDict = [[NSBundle mainBundle] infoDictionary];
    if (!infoDict) {
        return nil;
    }
    
    // Get CFBundleDocumentTypes
    NSArray*    types;
    types = [infoDict objectForKey:@"CFBundleDocumentTypes"];
    if (!types) {
        return nil;
    }
    
    // Enumerate document types
    NSEnumerator*   enumerator;
    NSDictionary*   type;
    enumerator = [types objectEnumerator];
    while (type = [enumerator nextObject]) {
        // Get MIME types
        NSArray*    mimeTypes;
        mimeTypes = [type objectForKey:@"CFBundleTypeMIMETypes"];
        if (!mimeTypes) {
            continue;
        }
        
        // Check MIME type
        NSEnumerator*   mimeEnumerator;
        NSString*       mime;
        mimeEnumerator = [mimeTypes objectEnumerator];
        while (mime = [mimeEnumerator nextObject]) {
            if ([mime isEqualToString:MIMEType]) {
                // Return type name
                return [type objectForKey:@"CFBundleTypeName"];
            }
        }
    }
    
    return nil;
}

@end
