/*
    ProjectAttributes.m

    Implementation of the ProjectAttributes class for the
    ProjectManager application.

    Copyright (C) 2005  Saso Kiselkov

    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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

#import "ProjectAttributes.h"

#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSNotification.h>

#import <AppKit/NSBox.h>
#import <AppKit/NSImage.h>
#import <AppKit/NSMenuItem.h>
#import <AppKit/NSNibLoading.h>
#import <AppKit/NSPanel.h>
#import <AppKit/NSTextField.h>
#import <AppKit/NSToolbarItem.h>

#import "../../ProjectDocument.h"
#import "../../ProjectType.h"
#import "../../NSImageAdditions.h"

#import "ProjectAttributesDelegate.h"

@implementation ProjectAttributes

+ (NSString *) moduleName
{
  return @"ProjectAttributes";
}

+ (NSString *) humanReadableModuleName
{
  return _(@"Attributes");
}

- (NSArray *) moduleMenuItems
{
  NSArray * tabIdentifiers = [delegate
    tabIdentifiersForProjectAttributes: self];
  NSMutableArray * array = [NSMutableArray arrayWithCapacity:
    [tabIdentifiers count] + 1];
  NSEnumerator * e;
  NSString * tabIdentifier;
  unsigned int i;

  [array addObject: PMMakeMenuItem (_(@"General"),
    @selector (showGeneralAttributes:), nil, self)];

  e = [tabIdentifiers objectEnumerator];
  for (i = 0; (tabIdentifier = [e nextObject]) != nil; i++)
    {
      NSMenuItem * item;
      NSString * label = [delegate projectAttributes: self
                    toolbarItemLabelForTabIdentifier: tabIdentifier];

      item = PMMakeMenuItem (label, @selector (switchView:), nil, self);
      [item setTag: i];

      [array addObject: item];
    }

  return [[array copy] autorelease];
}

- (NSArray *) toolbarItemIdentifiers
{
  // build the cache if needed
  if (delegateItemIdentifiers == nil)
    {
      int i, n;
      NSMutableArray * itemIdentifiers = [[[delegate
        tabIdentifiersForProjectAttributes: self] mutableCopy] autorelease];

      // prepend each identifier returned by the delegate with
      // @"ProjectAttributesDelegateItem: "
      for (i = 0, n = [itemIdentifiers count]; i < n; i++)
        {
          NSString * identifier = [@"ProjectAttributesDelegateItem: "
            stringByAppendingString: [itemIdentifiers objectAtIndex: i]];

          [itemIdentifiers replaceObjectAtIndex: i withObject: identifier];
        }

      ASSIGNCOPY (delegateItemIdentifiers, itemIdentifiers);
    }

  return [[NSArray arrayWithObject:
    @"ProjectAttributesShowGeneralAttributesItemIdentifier"]
    arrayByAddingObjectsFromArray: delegateItemIdentifiers];
}

- (NSToolbarItem *) toolbarItemForItemIdentifier: (NSString *) itemIdentifier
{
  NSToolbarItem * item = [[[NSToolbarItem alloc]
    initWithItemIdentifier: itemIdentifier]
    autorelease];

  [item setTarget: self];

  if ([itemIdentifier isEqualToString:
    @"ProjectAttributesShowGeneralAttributesItemIdentifier"])
    {
      [item setLabel: _(@"General")];
      [item setImage: [NSImage imageNamed: @"GeneralAttributes" owner: self]];
      [item setAction: @selector (showGeneralAttributes:)];
      [item setToolTip: _(@"Shows the general attributes of the project")];
    }
  else if ([itemIdentifier hasPrefix: @"ProjectAttributesDelegateItem: "])
    {
      int tag;
      NSImage * icon;
      NSString * label, * toolTip;
      NSString * tabIdentifier = [itemIdentifier
        stringByDeletingPrefix:  @"ProjectAttributesDelegateItem: "];

      tag = [delegateItemIdentifiers indexOfObject: itemIdentifier];
      label = [delegate projectAttributes: self
         toolbarItemLabelForTabIdentifier: tabIdentifier];
      toolTip = [delegate projectAttributes: self
         toolbarItemToolTipForTabIdentifier: tabIdentifier];
      icon = [delegate projectAttributes: self
         toolbarItemIconForTabIdentifier: tabIdentifier];

      [item setLabel: label];
      [item setToolTip: toolTip];
      [item setImage: icon];
      [item setAction: @selector (switchView:)];
      [item setTag: tag];
    }

  return item;
}

- (void) dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver: self];

  TEST_RELEASE (generalView);
  TEST_RELEASE (view);
  TEST_RELEASE (delegateItemIdentifiers);

  [super dealloc];
}

- initWithDocument: (ProjectDocument *) aDocument
    infoDictionary: (NSDictionary *) infoDict
{
  if ((self = [self init]) != nil)
    {
      document = aDocument;

      [[NSNotificationCenter defaultCenter]
        addObserver: self
           selector: @selector (projectNameChanged:)
               name: ProjectNameDidChangeNotification
             object: document];
    }

  return self;
}

- (ProjectDocument *) document
{
  return document;
}

- (NSView *) view
{
  if (view == nil)
    {
      [NSBundle loadNibNamed: @"ProjectAttributes" owner: self];
    }

  return view;
}

- (NSDictionary *) infoDictionary
{
  return nil;
}

- (BOOL) regenerateDerivedFiles
{
  return YES;
}

- (BOOL) validateMenuItem: (id <NSMenuItem>) item
{
  return YES;
}

- (BOOL) validateToolbarItem: (NSToolbarItem *) toolbarItem
{
  return YES;
}

- (void) awakeFromNib
{
  [view retain];
  [view removeFromSuperview];
  DESTROY (bogusWindow);

  [generalView retain];
  [generalView removeFromSuperview];
  DESTROY (generalBogusWindow);

  [projectName setStringValue: [document projectName]];
  [projectType setStringValue: [[[document projectType] class]
    humanReadableProjectTypeName]];

  [self switchView: nil];
}

- (void) finishInit
{
  delegate = (id <ProjectAttributesDelegate>) [document projectType];
}

/**
 * An action which switches the current view based on what toolbar
 * item has been selected.
 */
- (void) switchView: sender
{
  [document setCurrentProjectModule: self];

  if (sender == nil)
    {
      [view setContentView: generalView];
    }
  else
    {
      NSString * tabIdentifier = [[delegateItemIdentifiers objectAtIndex:
        [sender tag]] stringByDeletingPrefix:
        @"ProjectAttributesDelegateItem: "];

      [view setContentView: [delegate projectAttributes: self
                                   viewForTabIdentifier: tabIdentifier]];
    }
}

/**
 * Action invoked by the toolbar item to select the general project
 * attributes tab.
 */
- (void) showGeneralAttributes: sender
{
  [self switchView: nil];
}

/**
 * Action invoked when the user changes the project's name.
 */
- (void) changeProjectName: sender
{
  NSString * newProjectName = [projectName stringValue];
  NSError * error;

  if ([ProjectDocument validateProjectName: newProjectName error: &error])
    {
      [document setProjectName: newProjectName];
    }
  else
    {
      NSRunAlertPanel(_(@"Invalid project name"),
        _(@"%@."), nil, nil, nil, [[error userInfo] objectForKey:
        NSLocalizedDescriptionKey]);
    }
}

- (void) projectNameChanged: (NSNotification *) notif
{
  [projectName setStringValue: [document projectName]];
}

@end
