/*
    TemplateFileSelector.m

    Implementation of the TemplateFileDescriptor class for the ProjectManager
    app.

    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 "TemplateFileSelector.h"

#import <Foundation/NSString.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSNotification.h>

#import <AppKit/NSPanel.h>
#import <AppKit/NSBrowser.h>
#import <AppKit/NSTextView.h>
#import <AppKit/NSButton.h>
#import <AppKit/NSNibLoading.h>
#import <AppKit/NSMatrix.h>
#import <AppKit/NSBrowserCell.h>
#import <AppKit/NSApplication.h>
#import <AppKit/NSForm.h>
#import <AppKit/NSFormCell.h>
#import <AppKit/NSScrollView.h>

@implementation TemplateFileSelector : NSObject

static TemplateFileSelector * shared = nil;

+ shared
{
  if (shared == nil)
    {
      shared = [self new];
    }

  return shared;
}

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

  TEST_RELEASE(panel);

  TEST_RELEASE(directory);
  TEST_RELEASE(oldBrowserPath);

  [super dealloc];
}

- (void) awakeFromNib
{
  // watch when the text inside the form changes
  [[NSNotificationCenter defaultCenter]
    addObserver: self
       selector: @selector(updateSelection:)
           name: NSControlTextDidChangeNotification
         object: filename];

  filename = [(NSForm *) filename cellAtIndex: 0];

  [[fileDescription enclosingScrollView] setHasVerticalScroller: NO];
}

- (int) runModalForTemplatesDirectory: (NSString *) aDirectory
{
  int code;

  ASSIGN(directory, aDirectory);

  if (panel == nil)
    {
      [NSBundle loadNibNamed: @"TemplateFileSelector" owner: self];
    }

  [browser setPath: @"/"];
  [browser reloadColumn: 0];
  [filename setStringValue: nil];

  [self updateSelection: self];
  [importAssociatedButton setState: YES];

  [panel selectKeyViewFollowingView: okButton];

  [panel center];
  code = [NSApp runModalForWindow: panel];

  [panel close];

  return code;
}

- (NSString *) filename
{
  return [filename stringValue];
}

- (NSString *) templateFile
{
  return [directory stringByAppendingPathComponent: [browser path]];
}

- (NSString *) templateDirectory
{
  return directory;
}

- (BOOL) shouldImportAssociatedFiles
{
  return [importAssociatedButton state];
}

- (void) ok: sender
{
  [NSApp stopModalWithCode: NSOKButton];
}

- (void) cancel: sender
{
  [NSApp stopModalWithCode: NSCancelButton];
}

- (void) updateSelection: sender
{
  NSString * file;
  NSString * description;

  [okButton setEnabled: [[browser selectedCell] isLeaf] &&
    ([[filename stringValue] length] > 0)];

  file = [[directory stringByAppendingPathComponent: [browser path]]
    stringByAppendingPathExtension: @"pmdesc"];
  if (![file isEqualToString: oldBrowserPath])
    {
      ASSIGN(oldBrowserPath, file);

      if ([[NSFileManager defaultManager] fileExistsAtPath: file])
        {
          description = [NSString stringWithContentsOfFile: file];

          [fileDescription setString: description];
        }
      else
        {
          [fileDescription setString: nil];
        }
    }
}

- (void) browser: (NSBrowser *)sender createRowsForColumn: (int)column
  inMatrix: (NSMatrix *)matrix
{
  NSFileManager * fm = [NSFileManager defaultManager];
  NSString * path = [directory stringByAppendingPathComponent: [browser path]];
  NSDirectoryEnumerator * de = [fm enumeratorAtPath: path];
  NSString * file;

  while ((file = [de nextObject]) != nil)
    {
      NSDictionary * fileAttributes;
      NSBrowserCell * cell;

      // skip over ".pmdesc" files
      if ([[file pathExtension] isEqualToString: @"pmdesc"])
        {
          continue;
        }

      fileAttributes = [de fileAttributes];

      [matrix addRow];
      cell = [matrix cellAtRow: [matrix numberOfRows] - 1 column: 0];

      if ([[fileAttributes fileType] isEqualToString: NSFileTypeDirectory])
        {
          if ([[file pathExtension] length] > 0)
            {
              [cell setLeaf: YES];
              [de skipDescendents];
            }
          else
            {
              [cell setLeaf: NO];
            }
        }
      else
        {
          [cell setLeaf: YES];
        }

      [cell setTitle: [file lastPathComponent]];
    }
}

@end
