#include "filesele.h"
#include "button.h"
#include "messageb.h"
#include <dirent.h>

@implementation WDCFileSelectBox


- free
{
  XtFree(_fileName);
}

- initWithName:(char*)aName managedBy:anObject
{
  [self setWidget:XmCreateFileSelectionDialog([anObject getWidget], 
					      aName, NULL, 0)];
  [self setChildObject: [[WDCHelpMessageBox alloc] 
			 initWithName : "Error" managedBy:self]];

  // the following line is not working.

  [[self setArg:XmNx to:(void*)100] setArg:XmNy to:(void*)100];
  [self setParentObject:anObject];
  return [self setAction];
}


- setCallData:(XtPointer)aCall_data
{
  XmFileSelectionBoxCallbackStruct * aCall_data_ptr
    =(XmFileSelectionBoxCallbackStruct *)aCall_data;
  _call_data.reason=aCall_data_ptr->reason;
  _call_data.event=aCall_data_ptr->event;
  _call_data.value=aCall_data_ptr->value;
  _call_data.length=aCall_data_ptr->length;
  _call_data.mask=aCall_data_ptr->mask;
  _call_data.mask_length=aCall_data_ptr->mask_length;
  _call_data.dir=aCall_data_ptr->dir;
  _call_data.dir_length=aCall_data_ptr->dir_length;
  _call_data.pattern=aCall_data_ptr->pattern;
  _call_data.pattern_length=aCall_data_ptr->pattern_length;
  return self;
}

- setFileName:(char*)fileName
{
  _fileName=fileName;
  return self;
}

- (char*)getFileName
{
  return _fileName;
}

- getMessageBox
{
  return [self getChildObject];
}

- doCancel
{
  [self setFileName:0];
  [self doCancelAux];
  [[self getParentObject] unManageChild];
  return self;
}

- doSelected
{
  DIR * directory;

  if (!XmStringGetLtoR(_call_data.value,
		       XmSTRING_DEFAULT_CHARSET, &_fileName))
    {
      [[self getMessageBox] 
       setMessage : "Internal Error. Please try it again or <QUIT>", 0];
      [[self getMessageBox] manage];    
    }
  else if (directory=opendir([self getFileName]))
    {
      [[self getMessageBox] setMessage:"Please select a file or <QUIT>", 0];
      [[self getMessageBox] manage];
      close(directory);
      [self setFileName:0];
    }
  else
    {
      if ([self doSelectedAux])
	[[self getParentObject] unManageChild];
    }
  return self;
}

- doSelectedAux
{
  [super doAction];
  return self;
}

- doCancelAux
{
  return self;
}

- setAction
{
  XtAddCallback([self getWidget], XmNokCallback, theCallback, self);
  XtAddCallback([self getWidget], XmNcancelCallback, theCallback, self);  
  return self;
}

- doAction
{
  [self perform:sel_get_uid(_call_data.reason==31 ?
			     "doSelected" :
			     "doCancel")];
  return self;
}

- manage
{
  id child=[self getChildObject];
  [super manage];
  //  if (![child isManaged]) [child manage];
  return self;
}

- unManage
{
  id child=[self getChildObject];
  [super unManage];
  if ([child isManaged]) [child unManage];
  return self;
}  



@end


