/*
    PreferencesWindowController.m - Preferences window controller for Poe.app
    Copyright (C) 2003,2004,2005 Rob Burns

    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 02111, USA.
*/

#include "PreferencesWindowController.h"

static PreferencesWindowController *singleInstance = nil;

@implementation PreferencesWindowController

- (void) dealloc
{
  RELEASE(genreView);
  RELEASE(addButton);
  RELEASE(deleteButton);
  RELEASE(genreBrowser);
  RELEASE(genreText);

  RELEASE(_commentTags);
  RELEASE(_genres);

  RELEASE(label);
  
  [super dealloc];
} 

- (id) init
{
  self = [super initWithWindowNibName: @"Preferences" owner: self];

  [[self window] setTitle: _(@"Preferences")];
  [label setStringValue: _(@"Default comments to use:")];
  [tagDesc setString: _(@"If you find you want to use a tag that you haven't set to default, you can add any of the comment tags to a file, by selecting 'Add comment' from the 'Edit' menu when you are editing a file.")];

  [[self window] setFrameAutosaveName: @"Preferences"];
  [[self window] setFrameUsingName: @"Preferences"];

  [self _setupData];

  [self _setupTable];

  [self _setupGenreView];

  return self;
}

+ (id) singleInstance
{
  if( !singleInstance )
    {
      singleInstance = [[PreferencesWindowController alloc] init];
    }

  return singleInstance;
}

- (void) addGenre: (id)sender
{
  NSMutableArray *temp;

  temp = [[NSMutableArray alloc] initWithArray: 
    [[NSUserDefaults standardUserDefaults] arrayForKey: @"genresAdded"]];

  [temp addObject: [genreText stringValue]]; 
  [[NSUserDefaults standardUserDefaults]
    setObject: temp forKey: @"genresAdded"];

  [[NSUserDefaults standardUserDefaults] synchronize];

  [_genres insertObjectAlphabetically: [genreText stringValue]];

  [[NSNotificationCenter defaultCenter]
    postNotificationName: @"GenresDidChange" object: nil];

  RELEASE(temp);

  [genreBrowser reloadColumn: 0];
}

- (void) removeGenre: (id)sender;
{
  NSMutableArray *temp;
  NSString *theObject;
  int index;

  temp = [[NSMutableArray alloc] initWithArray:
    [[NSUserDefaults standardUserDefaults] arrayForKey: @"genresRemoved"]];

  theObject = [[genreBrowser selectedCell] stringValue];
	if (!theObject) return;

  index = [_genres indexOfObject: theObject];

  [temp addObject: theObject];
  [[NSUserDefaults standardUserDefaults]
    setObject: temp forKey: @"genresRemoved"];

  [[NSUserDefaults standardUserDefaults] synchronize];

  [_genres removeObjectAtIndex: index];

  [[NSNotificationCenter defaultCenter]
    postNotificationName: @"GenresDidChange" object: nil];

  RELEASE(temp);

  [genreBrowser reloadColumn: 0];
}

// Private methods
//***************** 

- (void) _setupData
{
  int i;

  NSArray *standardTags = [NSArray arrayWithArray: 
    [[Util singleInstance] tagsTitle]];
 
  NSArray *defaultTags = [[NSUserDefaults standardUserDefaults] 
    arrayForKey: @"defaultTags"];  
                                            
  _commentTags = [[NSMutableArray alloc] init];

  for(i=0;i<[standardTags count];i++)
    {
      if([defaultTags containsObject: [[Util singleInstance] tagAtIndex: i]])
        {
          [_commentTags addObject: [NSMutableDictionary 
            dictionaryWithObjectsAndKeys: [standardTags objectAtIndex: i], @"tag",
                                          [NSNumber numberWithInt: 1], @"used",
                                          nil]];
        }
      else
        {
          [_commentTags addObject: [NSMutableDictionary
            dictionaryWithObjectsAndKeys: [standardTags objectAtIndex: i], @"tag",
                                          [NSNumber numberWithInt: 0], @"used",
                                          nil]];
        }
    }

  _genres = [[NSMutableArray alloc] initWithArray: [[Util singleInstance] genres]];
}

- (void) _setupTable
{
  ExtendedTableColumn *tags,*used;
  NSButtonCell *cell;

  tags = AUTORELEASE([[NSTableColumn alloc] initWithIdentifier: @"tags"]);
  [tags setEditable: NO];
  [tags setWidth: 120];

  used = AUTORELEASE([[ExtendedTableColumn alloc] initWithIdentifier: @"used"]);
  [used setShouldUseAndSetState: YES];
  [used setShouldUseMouse: YES];
  [used setEditable: NO];
  [used setWidth: 40];
  cell = AUTORELEASE([[NSButtonCell alloc] init]);
  [cell setButtonType: NSSwitchButton];
  [cell setImagePosition: NSImageOnly];
  [used setDataCell: cell];

  tagsTable = [[SwitchTableView alloc] init];
  [tagsTable setDataSource: self];
  [tagsTable setDelegate: self];

  [tagsTable addTableColumn: tags];
  [tagsTable addTableColumn: used];

  [tagsTable setAllowsMultipleSelection: NO];
  [tagsTable setAllowsColumnSelection: NO];
  [tagsTable setDrawsGrid: NO];

  [tagsTable setRowHeight: [[NSFont systemFontOfSize:
    [NSFont systemFontSize]] boundingRectForFont].size.height+5];

  [tagsTableSV setDocumentView: tagsTable];
  [tagsTableSV setHasHorizontalScroller: NO];
  [tagsTableSV setHasVerticalScroller: YES];
  [tagsTableSV setBorderType: NSBezelBorder];
  
  [tagsTable setCornerView: nil];
  [tagsTable setHeaderView: nil];
}

- (void) _setupGenreView
{
  genreView = [[NSView alloc] initWithFrame: 
    NSMakeRect(0,0,228,133)];

  genreText = AUTORELEASE([[NSTextField alloc] initWithFrame:
    NSMakeRect(0,0,170,24)]);
  [genreText setTarget: self];
  [genreText setAction: @selector(addGenre:)];

  addButton = AUTORELEASE([[NSButton alloc] initWithFrame:
    NSMakeRect(175,0,24,24)]);
  [addButton setImagePosition: NSImageOnly];
  [addButton setImage: [NSImage imageNamed: @"B_add"]];
  [addButton setAction: @selector(addGenre:)];

  deleteButton = AUTORELEASE([[NSButton alloc] initWithFrame:
    NSMakeRect(204,0,24,24)]);
  [deleteButton setImagePosition: NSImageOnly];
  [deleteButton setImage: [NSImage imageNamed: @"B_remove"]];
  [deleteButton setAction: @selector(removeGenre:)];

  genreBrowser = AUTORELEASE([[NSBrowser alloc] initWithFrame:
    NSMakeRect(0,29,228,105)]);
  [genreBrowser setDelegate: self];
  [genreBrowser setTitled: NO];
  [genreBrowser setHasHorizontalScroller: NO];
  [genreBrowser setTarget:self];
  [genreBrowser setAction:@selector(click:)];
  [genreBrowser setMaxVisibleColumns:1];
  [genreBrowser setAllowsMultipleSelection:NO];
  [genreBrowser loadColumnZero];

  [genreBrowser setNextKeyView: genreText];
  [genreText setNextKeyView: addButton];
  [addButton setNextKeyView: deleteButton];
  [deleteButton setNextKeyView: genreBrowser];

  [genreView addSubview: genreText];
  [genreView addSubview: addButton];
  [genreView addSubview: deleteButton];
  [genreView addSubview: genreBrowser];
}

// NSTable data source protocol methods
//**************************************

- (int) numberOfRowsInTableView: (NSTableView *)aTableView;
{
  return [_commentTags count];
}

- (id)            tableView: (NSTableView *)aTableView
  objectValueForTableColumn: (NSTableColumn *)aTableColumn
                        row: (int)rowIndex;
{
  if(aTableColumn != nil)
    {
      if([[aTableColumn identifier] isEqualToString: @"tags"])
        {
          return [[_commentTags objectAtIndex: rowIndex] objectForKey: @"tag"];
        }
    }

  return nil;
}


// SwitchTableView data source protocol methods
//**********************************************

- (int)    tableView: (NSTableView *)aTableView
 stateForTableColumn: (NSTableColumn *)aTableColumn
                 row: (int)rowIndex;
{
  if(aTableColumn != nil)
    {
      if([[aTableColumn identifier] isEqualToString: @"used"])
        {
          return [[[_commentTags objectAtIndex: rowIndex] objectForKey: @"used"] intValue];
        }
    }

  return 0;
}

- (void)   tableView: (NSTableView *)aTableView
            setState: (int)aState
      forTableColumn: (NSTableColumn *)aTableColumn
                 row: (int)rowIndex;
{
  NSMutableArray *dt;
  NSUserDefaults *defaults;
  NSString *item;

  defaults = [NSUserDefaults standardUserDefaults];
  dt = [NSMutableArray arrayWithArray: [defaults arrayForKey: @"defaultTags"]];
  item = [[Util singleInstance] tagAtIndex: rowIndex];

  if(aTableColumn !=nil && rowIndex >= 0)
    {
      if([[aTableColumn identifier] isEqualToString: @"used"])
        {
          [[_commentTags objectAtIndex: rowIndex] setObject:
            [NSNumber numberWithInt: aState] forKey: @"used"];

          if([dt containsObject: item])
            {
              [dt removeObject: item];
              [defaults setObject: dt forKey: @"defaultTags"];
            }
          else
            {
              [dt addObject: item];
              [defaults setObject: dt forKey: @"defaultTags"];
            }
          [defaults synchronize];
        }
    }
}

// NSTableView delegate methods
//******************************

- (void)tableViewSelectionIsChanging:(NSNotification *)aNotification
{
  if([[[Util singleInstance] tagAtIndex: [tagsTable selectedRow]] 
    isEqualToString: @"GENRE"])
    {
      descView = RETAIN([box contentView]);
      [box setContentView: genreView];
      [box display];
      gvFlag = 1;
    }
  else if(gvFlag)
    {
      RETAIN(genreView);
      [box setContentView: descView];
      [tagDesc setString: [[Util singleInstance] 
        descriptionAtIndex: [tagsTable selectedRow]]];
      [box display];
      gvFlag = 0;
    }
  else
    {
      [tagDesc setString: [[Util singleInstance]
        descriptionAtIndex: [tagsTable selectedRow]]];
    }
}

// NSBrowser delegate methods
//****************************

- (int)browser:(NSBrowser *)sender numberOfRowsInColumn:(int)column
{
  if(sender == genreBrowser)
    {
      return [_genres count];
    }

  return 0;
}

- (void)browser:(NSBrowser *)sender willDisplayCell:(id)cell
  atRow:(int)row column:(int)column
{
  if(sender == genreBrowser)
    {
      [cell setLeaf: YES];
      [cell setStringValue: [_genres objectAtIndex: row]];
    }
}

@end
