/*
**  PlopFolio.m
**
**  Copyright (c) 2002
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**
**  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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#import "PlopFolio.h"

#import "Channel.h"
#import "Constants.h"
#import "Plop.h"
#import "PlopWindowController.h"
#import "PreferencesPanelController.h"

// XML header needed under GNUstep
#ifndef MACOSX
#import <Foundation/GSXML.h>
#endif

@implementation PlopFolio

//
//
//
- (id) init
{
  self = [super init];
  
  return self;
}


//
//
//
- (void) dealloc
{
  RELEASE(allPlops);

  [super dealloc];
}


//
// action methods
//
- (IBAction) showPreferencesPanel: (id) sender
{
  PreferencesPanelController *aController;

  aController = [[PreferencesPanelController alloc] initWithWindowNibName: @"PreferencesPanel"];
  
  [[aController window] orderFront: nil];
  //[NSApp runModalForWindow: [aController window]];
}


//
// delegate methods
//
- (void) applicationDidFinishLaunching: (NSNotification *) not
{
  NSFileManager *aFileManager;
  BOOL isDir;

  aFileManager = [NSFileManager defaultManager];
  
  if ( [aFileManager fileExistsAtPath: (NSString *)PlopFolioUserLibraryPath()
		     isDirectory: &isDir] )
    {
      if ( !isDir )
        {
          NSLog(@"%@ exists but it is a file not a directory.",
                PlopFolioUserLibraryPath());
          exit(1);
        }
    }
  else
    {
      if ( ![aFileManager createDirectoryAtPath: (NSString *)PlopFolioUserLibraryPath()
			  attributes: nil] )
	{
	  // directory creation failed.  quit.
	  NSLog(@"Could not create directory: %@", PlopFolioUserLibraryPath());
	  exit(1);
	}
      else
        {
          NSLog(@"Created directory: %@", PlopFolioUserLibraryPath());
        }
    }


  // We verify if our archived NSMutableArray exists, if not,
  // we create. If yes, we decode it.
  if ( [aFileManager fileExistsAtPath: PathToPlops()] )
    {
      allPlops = [NSUnarchiver unarchiveObjectWithFile: PathToPlops()];
      RETAIN(allPlops);
    }
  else
    {
      allPlops = [[NSMutableArray alloc] init];
      [self synchronize];
    }
  
  [self showAllPlops];

}


//
//
//
#ifdef MACOSX
- (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication *) theSender
#else
- (BOOL) applicationShouldTerminate: (NSApplication *) theSender
#endif
{
  [self synchronize];

  return YES;
}


//
//
//
- (void) applicationWillFinishLaunching: (NSNotification *) not
{
  // Local variable
#ifndef MACOSX  
  SEL action = NULL;
#endif

  // We begin by setting our NSApp's logo
  [NSApp setApplicationIconImage: [NSImage imageNamed: @"PlopFolio.tiff"]];
  
    // We continue by creating our NSMenu
#ifndef MACOSX
  menu = [[NSMenu alloc] init];
  
  [menu addItemWithTitle:_(@"Info") action: action keyEquivalent: @""];
  [menu addItemWithTitle:_(@"Edit") action: action  keyEquivalent: @""];
  [menu addItemWithTitle:_(@"Windows") action: action keyEquivalent: @"p"];
  [menu addItemWithTitle:_(@"Print") action: action keyEquivalent: @"p"];
  [menu addItemWithTitle:_(@"Services") action: action keyEquivalent: @""];
  [menu addItemWithTitle:_(@"Hide") action: @selector (hide:) keyEquivalent: @"h"];
  [menu addItemWithTitle:_(@"Quit") action:@selector(terminate:) keyEquivalent: @"q"];

  // Our Info menu / submenus
  info = [[NSMenu alloc] init];
  [menu setSubmenu:info forItem:[menu itemWithTitle:_(@"Info")]];
  [info addItemWithTitle:_(@"Info Panel...")
        action: @selector(orderFrontStandardInfoPanel:)   
        keyEquivalent:@""];
  [info addItemWithTitle:_(@"Preferences...")
        action: @selector(showPreferencesPanel:)
        keyEquivalent:@""];
  [info addItemWithTitle:_(@"Help...")
        action: action
        keyEquivalent:@"?"];
  RELEASE(info);

  // Our Edit menu / submenus
  edit = [[NSMenu alloc] init];
  [menu setSubmenu:edit forItem:[menu itemWithTitle:_(@"Edit")]];
  [edit addItemWithTitle: _(@"Cut")
	action: @selector(cut:)
	keyEquivalent: @"x"];
  [edit addItemWithTitle: _(@"Copy")
	action: @selector(copy:)
	keyEquivalent: @"c"];
  [edit addItemWithTitle: _(@"Paste")
	action: @selector(paste:)
	keyEquivalent: @"v"];
  [edit addItemWithTitle: _(@"Delete")
	action: @selector(delete:)
	keyEquivalent: @""];
  [edit addItemWithTitle: _(@"Select All")
	action: @selector(selectAll:)
	keyEquivalent: @"a"];
  RELEASE(edit);

  // Our Windows menu
  windows = [[NSMenu alloc] init];
  [menu setSubmenu:windows forItem: [menu itemWithTitle:_(@"Windows")]];

  // Our Services menu
  services = [[NSMenu alloc] init];
  [menu setSubmenu: services forItem: [menu itemWithTitle: _(@"Services")]];

  [NSApp setMainMenu: menu];
  [NSApp setServicesMenu: services];
  [NSApp setWindowsMenu: windows];

  RELEASE(services);
  RELEASE(windows);
  RELEASE(menu);
#endif
}


#ifdef MACOSX
- (void) awakeFromNib
{
  dockMenu = [[NSMenu alloc] init];
  [dockMenu setAutoenablesItems: NO];
}


- (NSMenu *) applicationDockMenu: (NSApplication *) sender
{
    return dockMenu;
}
#endif


//
// other methods
//
- (void) showAllPlops
{
  int i;
  
  // We show all the Plops
  for (i = 0; i < [allPlops count]; i++)
    {
      [self showPlop: [allPlops objectAtIndex: i]];
    }
}


//
//
//
- (void) showPlop: (Plop *) thePlop
{
  PlopWindowController *aPlopWindowController;
  Channel *aChannel;

  if ( ![thePlop isActive] )
    {
      // We verify if it had an opened channel. If so, we close the channel.
      if ( [thePlop channel] )
	{
	  NSLog(@"Must close the channel!");
	  [[[thePlop channel] plopWindowController] close];
	}
      
      return;
    }
  else
    {
      // If the plop is active and has a channel, we simply do NOTHING here.
      if ( [thePlop channel] )
	{
	  return;
	}
    }
  
  // The plop is active but has no channel, let's create a channel for this plop.
  aChannel = [[Channel alloc] init];
  [aChannel setPlop: thePlop];
  [aChannel update: self];

  aPlopWindowController = [[PlopWindowController alloc] initWithWindowNibName: @"PlopWindow"];
  [aPlopWindowController setChannel: aChannel];  
  [[aPlopWindowController window] orderFront: nil];
  
  RELEASE(aChannel);
}


//
//
//
- (BOOL) synchronize
{
  return [NSArchiver archiveRootObject: allPlops
		     toFile: PathToPlops()];
}


//
// access / mutation methods
//
- (NSMutableArray *) allPlops
{
  return allPlops;
}

//
// static methods
//

@end


//
// Starting point for Terminal.app
//
int main(int argc, const char *argv[], char *env[])
{     
  NSAutoreleasePool *pool;
  PlopFolio *plop;
  
  pool = [[NSAutoreleasePool alloc] init];
  plop = [[PlopFolio alloc] init];
  
  [NSApplication sharedApplication];
  [NSApp setDelegate: plop];

  NSApplicationMain(argc, argv); 
  
  RELEASE(plop);
  RELEASE(pool);
  
  return 0;
}
