/*
 * For legal stuff see the file COPYRIGHT
 */
#import "Preferences.h"

@implementation Preferences

/* Attribute defaults */
#define	DFLT_INVOICE_NUM	"0"
#define DFLT_INVOICE_DIR	"/tmp"
#define DFLT_HIDE_ON_AUTO	"NO"

static BOOL
yes( const char *attr )
{
  const char *value = GET_DEFAULT(attr);

  return ( value && strcmp( value, "YES") ? YES : NO );
}

+ initialize
{
  static NXDefaultsVector dflts = {
    { INVOICE_NUM,	 	DFLT_INVOICE_NUM },
    { INVOICE_DIR,	 	DFLT_INVOICE_DIR },
    { HIDE_ON_AUTO,	 	DFLT_HIDE_ON_AUTO },
    { NULL }
  };

  NXRegisterDefaults( OWNER, dflts ) ;
  return self ;
}

/*
 * Allow only one preferences object for this app
 */
+ new
{
  static id prefs;

  if ( ! prefs ) {
    prefs = [[Preferences alloc] init];
    [NXApp loadNibSection:"Preferences.nib" owner:prefs withNames:NO];
    [prefs revert:nil];
  }
    
  return prefs;
}

/*
 * Called by the controller to see if we should hide ourselves.
 * Return YES if we were autolaunched and the user said to hide.
 */
- (BOOL)hideOnAutoLaunch
{
  
  return( yes( "NXAutoLaunch" ) && yes(HIDE_ON_AUTO) );
}

- display
{
  [invoiceNumberText selectText:nil];
  [window makeKeyAndOrderFront:self];
  return self;
}

- chooseDir:sender
{
  OpenPanel *panel = [OpenPanel new];
  int result;

  [panel chooseDirectories:YES];
  result = [panel runModalForDirectory:NXHomeDirectory() file:""];
  if ( result != NX_RUNABORTED )
    [directoryText setStringValue:[panel filename]];
  return self;
}

- ok:sender
{
  PUT_DEFAULT( INVOICE_NUM, [invoiceNumberText stringValue] ) ;
  PUT_DEFAULT( INVOICE_DIR, [directoryText stringValue] ) ;
  PUT_DEFAULT( HIDE_ON_AUTO,[hideButton state] ? "YES" : "NO" ) ;
  [window close];
  return self;
}

- revert:sender
{
  NXUpdateDefaults() ;		/* reload the table from the database */

  [invoiceNumberText setStringValue:GET_DEFAULT(INVOICE_NUM)];
  [directoryText     setStringValue:GET_DEFAULT(INVOICE_DIR)];
  [hideButton        setState:yes(HIDE_ON_AUTO)];
  return self;
}

- reset:sender
{
  [invoiceNumberText setStringValue:DFLT_INVOICE_NUM];
  [directoryText     setStringValue:DFLT_INVOICE_DIR];
  [hideButton        setState:yes(DFLT_HIDE_ON_AUTO)];
  return self;
}

@end
