//
// DocumentController.j
// Editor
//
// Created by Francisco Tolmasky.
// Copyright 2005 - 2008, 280 North, Inc. All rights reserved.
//

import <AppKit/CPDocumentController.j>

import "OpenPanel.j"
import "Themes.j"
import "ThemePanel.j"
import "WelcomePanel.j"


@implementation DocumentController : CPDocumentController
{
    BOOL    _applicationHasFinishedLaunching;
}

- (void)applicationDidFinishLaunching:(CPNotification)aNotification
{
    // FIXME
    // Check [CPApp arguments][0] for "docs" and [self openPresentationWithFilename: args[2]];

    [CPApp runModalForWindow:[[WelcomePanel alloc] init]];
    
    _applicationHasFinishedLaunching = YES;
}

- (void)newDocument:(id)aSender
{
    if (!_applicationHasFinishedLaunching)
        return [super newDocument:aSender];
    
    [[ThemePanel sharedThemePanel]
        beginWithInitialSelectedSlideMaster:SaganThemeSlideMaster 
                              modalDelegate:self
                             didEndSelector:@selector(themePanel:didEndWithReturnCode:)
                                contextInfo:YES];
}

- (void)themePanel:(ThemePanel)aThemePanel didEndWithReturnCode:(unsigned)aReturnCode
{
    if (aReturnCode == CPCancelButton)
        return;

    var documents = [self documents],
        count = [documents count];
        
    while (count--)
        [self removeDocument:documents[0]];
    
    [super newDocument:self];
}

- (void)openDocument:(id)aSender
{
    [[OpenPanel openPanel] beginWithModalDelegate:self didEndSelector:@selector(openPanelDidEnd:returnCode:contextInfo:) contextInfo:nil];
}

- (void)openPanelDidEnd:(OpenPanel)anOpenPanel returnCode:(unsigned)aReturnCode contextInfo:(id)aContextInfo
{
    if (aReturnCode == CPCancelButton)
        return;
    
    var filenames = [anOpenPanel filenames];
    
    [self openDocumentWithContentsOfURL:BASE_URL + @"document.php?documentName=" + encodeURIComponent(filenames[0]) display:YES error:nil];
}

// Only allow one open document at a time.
- (void)addDocument:(CPDocument)aDocument
{
    var documents = [self documents],
        count = [documents count];
    
    if (count)
        while (count--)
            [self removeDocument:documents[count]];
            
    [super addDocument:aDocument];
}

@end
