/*
**  DocumentController.m
**
**  Copyright (c) 2003
**
**  Author: Yen-Ju Chen <yjchenx@hotmail.com>
**
**  This program is free software; you can redistribute it and/or modify
**  it under the terms of the GNU General Public License as published by
**  the Free Software Foundation; either version 2 of the License, or
**  (at your option) any later version.
**
**  This program is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**  GNU General Public License for more details.
**
**  You should have received a copy of the GNU General Public License
**  along with this program; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "DocumentController.h"
#include "Document.h"
#include "Utilities.h"
#include "FindManager.h"
#include "Inspector.h"
#include "MethodViewer.h"
#include "FontAttributesManager.h"
#include "PreferenceManager.h"
#include "ScriptManager.h"
#include "STScriptingSupport.h"
#include <CodeEditorView/CodeEditorView.h>
#include <CodeEditorView/CodeEditorViewPreference.h>
#include <AppKit/AppKit.h>

@implementation DocumentController

/* StepTalk Support */
- (ScriptManager *) scriptManager
{
  return [ScriptManager sharedScriptManager];
}

- (CodeEditorView *) currentCodeEditorView
{
  return [[self scriptManager] currentCodeEditorView];
}

/* Application Delegate */

- (void) showFontAttributesPanel: (id) sender
{
  [[FontAttributesManager sharedFontAttributesManager] 
         orderFrontFontAttributesPanel: self];
}

- (void) showPrefPanel: (id) sender
{
  [[PreferenceManager sharedPreferenceManager]
         runModalPreferencePanel: self];
}

- (BOOL) applicationShouldTerminateAfterLastWindowClosed: (id)sender
{
  /* If last window close, close all panels */
  [[[Inspector sharedInspector] inspectorPanel] performClose: sender];
  [[[FindManager sharedFindManager] findPanel] performClose: sender];
  [[[MethodViewer sharedMethodViewer] methodPanel] performClose: sender];
  [[Inspector sharedInspector] setCodeEditorView: nil];
  [[FindManager sharedFindManager] setCodeEditorView: nil];
  [[MethodViewer sharedMethodViewer] setCodeEditorView: nil];  
  [[ScriptManager sharedScriptManager] setCodeEditorView: nil];
  return NO;
}

- (void) applicationDidFinishLaunching: (NSNotification *) not
{
  /* Load user default */
  id object;
  BOOL bool;
  float floatValue;
  int intValue;
  NSArray *filesFromArguments;
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  CodeEditorViewPreference *preference = 
      [CodeEditorViewPreferenceClass() sharedCodeEditorViewPreference];

  if ((object = [defaults objectForKey: @"Tab"]));
    [preference setTab: object];
  if ((bool = [defaults boolForKey: @"AutoFontification"]));
    [preference setAutoFontification: bool];
  if ((floatValue = [defaults floatForKey: @"FontificationInterval"]))
    [preference setFontificationInterval: floatValue];
  if ((bool = [defaults boolForKey: @"AutoFontificationThreshold"]))
    [preference setAutoFontificationThreshold: bool];
  if ((intValue = [defaults integerForKey: @"FontificationThreshold"]))
    [preference setFontificationThreshold: (unsigned)intValue];
  if ((bool = [defaults boolForKey: @"AutoFontificationEachLineWhenTyping"]))
    [preference setAutoFontificationEachLine: bool];
  if ((bool = [defaults boolForKey: @"AutoMarkBlock"]))
    [preference setAutoMarkBlock: bool];
  if ((bool = [defaults boolForKey: @"AutoMarkThreshold"]))
    [preference setAutoMarkThreshold: bool];
  if ((intValue = [defaults integerForKey: @"MarkThreshold"]))
    [preference setMarkThreshold: (unsigned)intValue];
  if ((bool = [defaults boolForKey: @"AutoIndentation"]))
    [preference setAutoIndentation: bool];
  if ((bool = [defaults boolForKey: @"DisplaySideView"]))
    [preference setDisplaySideView: bool];
  
  /* Open files from command if exist */
  filesFromArguments = [[NSProcessInfo processInfo] arguments];

  if([filesFromArguments count] > 1)
    {
      int i;
      id object;
      
      /* open in window */
      for (i = 1; i < [filesFromArguments count]; i++)
        {
          object = [[filesFromArguments objectAtIndex: i] stringByStandardizingPath];
          [self openDocumentWithContentsOfFile: object
                                       display: YES];
        }
    }
}

- (void) applicationWillFinishLaunching: (NSNotification *) not
{
  NSMenu *menu;
  NSMenu *infoMenu;
  NSMenu *documentMenu;
  NSMenu *editMenu;
  NSMenu *viewMenu;
  NSMenu *windowsMenu;
  NSMenu *servicesMenu;

  menu = [[NSMenu alloc] initWithTitle: _(@"Code Editor")];

  [menu addItemWithTitle: _(@"Info")
                  action: NULL
           keyEquivalent: @""];
  [menu addItemWithTitle: _(@"Document")
                  action: NULL
           keyEquivalent: @""];
  [menu addItemWithTitle: _(@"Edit")
                  action: NULL
           keyEquivalent: @""];
  [menu addItemWithTitle: _(@"Tools")
                  action: NULL
           keyEquivalent: @""];
  [menu addItemWithTitle: _(@"Windows")
                  action: NULL
           keyEquivalent: @""];
  [menu addItemWithTitle: _(@"Services")
                  action: NULL
           keyEquivalent: @""];
  if ([NSApp isScriptingSupported])
    {
      [menu addItemWithTitle: _(@"Scripting")
                      action: NULL
               keyEquivalent: @""];
    }
  [menu addItemWithTitle: _(@"Hide")
                  action: @selector(hide:)
           keyEquivalent: @"h"];
  [menu addItemWithTitle: _(@"Quit")
                  action: @selector(terminate:)
           keyEquivalent: @"q"];
  
  // Create the info submenu
  infoMenu = [[NSMenu alloc] initWithTitle: _(@"Info")];
   
  [infoMenu addItemWithTitle: _(@"Info Panel...")
                      action: @selector(orderFrontStandardInfoPanel:)
               keyEquivalent: @"i"];
  [infoMenu addItemWithTitle: _(@"Preferences...")
                      action: @selector(showPrefPanel:)
               keyEquivalent: @"p"];
  [infoMenu addItemWithTitle: _(@"Help")
                      action: @selector(orderFrontHelpPanel:)
               keyEquivalent: @"?"];
  [menu setSubmenu: infoMenu
           forItem: [menu itemWithTitle: _(@"Info")]];
  RELEASE(infoMenu);

  // Create the document submenu

  documentMenu = [[NSMenu alloc] initWithTitle: _(@"Document")];

  [documentMenu addItemWithTitle: _(@"Open")
                          action: @selector(openDocument:)
                   keyEquivalent: @"o"];
  [documentMenu addItemWithTitle: _(@"New")
                          action: @selector(newDocument:)
                   keyEquivalent: @"n"];
  [documentMenu addItemWithTitle: _(@"Save")
                          action: @selector(saveDocument:)
                   keyEquivalent: @"s"];
  [documentMenu addItemWithTitle: _(@"Save To...")
                          action: @selector(saveDocumentTo:)
                   keyEquivalent: @""];
  [documentMenu addItemWithTitle: _(@"Save As...")
                          action: @selector(saveDocumentAs:)
                   keyEquivalent: @""];
  [documentMenu addItemWithTitle: _(@"Save All")
                          action: @selector(saveAllDocuments:)
                   keyEquivalent: @"S"];
  [documentMenu addItemWithTitle: _(@"revert to Saved")
                          action: @selector(revertDocumentToSaved:)
                   keyEquivalent: @""];
  [documentMenu addItemWithTitle: _(@"Close Window")
                          action: @selector(performClose:)
                   keyEquivalent: @""];
  [menu setSubmenu: documentMenu
           forItem: [menu itemWithTitle: _(@"Document")]];
  RELEASE(documentMenu);

  // Create the edit submenu
  editMenu = [[NSMenu alloc] initWithTitle: _(@"Edit")];
  [editMenu addItemWithTitle: _(@"Cut")
                          action: @selector(cut:)
                   keyEquivalent: @"x"];
  [editMenu addItemWithTitle: _(@"Copy")
                          action: @selector(copy:)
                   keyEquivalent: @"c"];
  [editMenu addItemWithTitle: _(@"Paste")
                          action: @selector(paste:)
                   keyEquivalent: @"v"];
  [editMenu addItemWithTitle: _(@"Select All")
                          action: @selector(selectAll:)
                   keyEquivalent: @"a"];
  [editMenu addItemWithTitle: _(@"Refontify")
                          action: @selector(refontify:)
                   keyEquivalent: @"f"];
  [editMenu addItemWithTitle: _(@"Mark Current Block")
                          action: @selector(markCurrentBlock:)
                   keyEquivalent: @"b"];
  [menu setSubmenu: editMenu
           forItem: [menu itemWithTitle: _(@"Edit")]];
  RELEASE(editMenu);

  // Create the view submenu
  viewMenu = [[NSMenu alloc] initWithTitle: _(@"Tools")];
  [viewMenu addItemWithTitle: _(@"Toolbar")
                      action: @selector(showToolbarView:)
               keyEquivalent: @"t"];
  [viewMenu addItemWithTitle: _(@"Side View")
                      action: @selector(showSideView:)
               keyEquivalent: @"w"];
  [viewMenu addItemWithTitle: _(@"Inspector")
                      action: @selector(showInspector:)
               keyEquivalent: @"I"];
  [viewMenu addItemWithTitle: _(@"Find and Replace")
                      action: @selector(showFindPanel:)
               keyEquivalent: @"F"];
  [viewMenu addItemWithTitle: _(@"Font Attributes")
                      action: @selector(showFontAttributesPanel:)
               keyEquivalent: @""];
  [viewMenu addItemWithTitle: _(@"Methods")
                      action: @selector(showMethodViewer:)
               keyEquivalent: @"M"];

  [menu setSubmenu: viewMenu
           forItem: [menu itemWithTitle: _(@"Tools")]];
  RELEASE(viewMenu);

  // Create the windows submenu
  windowsMenu = [NSMenu new];

  [windowsMenu addItemWithTitle: _(@"Arrange")
                     action: @selector(arrangeInFront:)
              keyEquivalent: @""];
  [windowsMenu addItemWithTitle: _(@"Miniaturize")
                     action: @selector(performMiniaturize:)
              keyEquivalent: @"m"];
  [menu setSubmenu: windowsMenu
           forItem: [menu itemWithTitle: _(@"Windows")]];
  [NSApp setWindowsMenu: windowsMenu];
  RELEASE(windowsMenu);

  // Create the service submenu
  servicesMenu = [[NSMenu alloc] initWithTitle: _(@"Services")];
  [menu setSubmenu: servicesMenu
           forItem: [menu itemWithTitle: _(@"Services")]];
  [NSApp setServicesMenu: servicesMenu];
  RELEASE(servicesMenu);

  // Create the script submenu
  if ([NSApp isScriptingSupported])
    {
      [menu setSubmenu: [NSApp scriptingMenu]
               forItem: [menu itemWithTitle: _(@"Scripting")]];
    }

  [NSApp setMainMenu: menu];

  RELEASE(menu);
}

- (void) applicationWillTerminate: (NSNotification *) not
{
  /* Write user defaults */
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  CodeEditorViewPreference *preference =
    [CodeEditorViewPreferenceClass() sharedCodeEditorViewPreference];

  [defaults setObject: [preference tab] forKey: @"Tab"];
  [defaults setBool: [preference autoFontification] 
             forKey: @"AutoFontification"];
  [defaults setFloat: [preference fontificationInterval] 
              forKey: @"FontificationInterval"];
  [defaults setBool: [preference autoFontificationThreshold] 
             forKey: @"AutoFontificationThreshold"];
  [defaults setInteger: (int)[preference fontificationThreshold]
                forKey: @"FontificationThreshold"];
  [defaults setBool: [preference autoFontificationEachLine]
             forKey: @"AutoFontificationEachLineWhenTyping"];
  [defaults setBool: [preference autoMarkBlock]
             forKey: @"AutoMarkBlock"];
  [defaults setBool: [preference autoMarkThreshold]
             forKey: @"AutoMarkThreshold"];
  [defaults setInteger: [preference markThreshold]
                forKey: @"MarkThreshold"];
  [defaults setBool: [preference autoIndentation]
             forKey: @"AutoIndentation"];
  [defaults setBool: [preference displaySideView]
             forKey: @"DisplaySideView"];
 
  [defaults synchronize];
}

@end
