/*+++*
 *  title:	compat.m
 *  abstract:	OPENSTEP/Rhapsody compatibility routines for mailapp-utilities. 
 *  author:	Tom Hageman <tom@basil.icce.rug.nl>
 *  created:	January 1998
 *  modified:	(see RCS Log at end)
 *  copyleft:
 *
 *	Copyright (C) 1998 Tom R. Hageman, but otherwise perfect freeware.
 *
 *  description:
 *
 *---*/

static const char * const RCSid = ((void)&RCSid,
	"@(#)compat.m,v 1.4 1998/02/15 17:03:18");
#define RCS_compat_ID

#import "compat.h"

#define NSSTRING(s)  [NSString stringWithCString:(s)]

#if (OPENSTEP || RHAPSODY)

#import <Foundation/Foundation.h>

#if RHAPSODY

// {{OPENSTEP 4.2 still has NXGetDefault() in System.framework}}

@interface NSUserDefaults (OtherDomains)
+ (NSUserDefaults *)userDefaultsForDomainNamed:(NSString *)aDomain;
@end

static void setupDefaults(NSUserDefaults *defaults, NSString *aDomain)
{
   NSMutableArray *searchList = [NSMutableArray arrayWithArray:[defaults searchList]];

   [searchList insertObject:aDomain atIndex:0];
   [defaults setSearchList:searchList];
}

@implementation NSUserDefaults (OtherDomains)
+ (NSUserDefaults *)userDefaultsForDomainNamed:(NSString *)aDomain
{
   static NSMutableDictionary *defaultsByDomain = nil;
   NSUserDefaults *defaults;

   if ((defaults = [defaultsByDomain objectForKey:aDomain]) == nil)
   {
      defaults = [[NSUserDefaults alloc] init];
      setupDefaults(defaults, aDomain);
      if (defaultsByDomain == nil)
      {
	 defaultsByDomain = [[NSMutableDictionary alloc] initWithCapacity:1];
      }
      [defaultsByDomain setObject:defaults forKey:aDomain];
      [defaults release]; // retained by dictionary.
   }
   return defaults;
}
@end

static NSUserDefaults *userDefaultsForOwner(NSString *owner)
{
   return [NSUserDefaults userDefaultsForDomainNamed:owner];
}

extern const char *NXGetDefaultValue(const char *owner, const char *name)
{
   if (strcmp(owner, "GLOBAL") == 0) owner = "NSGlobalDomain"; // Cheat.

   return [[[userDefaultsForOwner(NSSTRING(owner))
	     objectForKey:NSSTRING(name)] description] cString];
   /* {{Note this is not the same as -stringForKey, which returns non-nil
      only if value is a string, and nil for array/dictionary objects.}} */
}

#endif // RHAPSODY

const char *NXHomeDirectory()
{
   return [NSHomeDirectory() cString];
}

const char *NXUserName()
{
   return [NSUserName() cString];
}

#endif // (OPENSTEP || RHAPSODY)
