/*
 * For legal stuff see the file COPYRIGHT
 */
#import <sys/time.h>
#import <stdio.h>
#import <stdlib.h>
#import "Session.h"

extern void freeAndCopy( char **ptr, const char *str );
extern char *NXCopyStringBuffer(const char *buffer);

@implementation Session

- init:(const char *)startDate
       time:(const char *)startTime
       duration:(int)elapsedMinutes
       description:(const char *)desc
{
  [self setStartDateString:startDate];
  [self setStartTimeString:startTime];
  [self setDescription:desc];
  minutes = elapsedMinutes;
  return self;
}

- (void) freeDesc
{
  if ( description ) {
    free( description );
    description = NULL;
  }
}

- free
{
  [self freeDesc];
  return [super free];
}

- setMinutes:(int)value
{
  minutes = value;
  return self;
}

/* Must we parse the string and convert to UNIX format? Why bother? */
- setStartDateString:(const char *)str
{
  freeAndCopy( &startDateString, str );
  return self;
}

- setStartTimeString:(const char *)str
{
  freeAndCopy( &startTimeString, str );
  return self;
}

- setDescription:(const char *)desc
{
  [self freeDesc];
  description = NXCopyStringBuffer(desc);
  return self;
}

- (const char *)startTimeString
{
  return startTimeString;
}

- (const char *)startDateString
{
  return startDateString;
}

- (const char *)description
{
  return description;
}

- (int)minutes
{
  return minutes;
}

- (float)hours
{
  return minutes/60.0;
}

/*
 * For use in comparisons, convert date such as 11/21/93 to a
 * single integer 932111. THIS SHOULD BE CACHED! (TBD)
 */
- (int)dateValue
{
  int day, month, year;

  sscanf( startDateString, "%d/%d/%d", &month, &day, &year );
  return ( year * 10000 + month * 100 + day );
}

/*
 * Similarly, convert 12:45 to the integer 1245.
 */
- (int)timeValue
{
  int minute, hour;

  sscanf( startTimeString, "%d:%d", &hour, &minute );
  return ( hour * 100 + minute );
}

- read:(NXTypedStream *) stream
{
  NXReadTypes( stream, "***i", &description, &startTimeString,
	      &startDateString, &minutes );
  return self;
}

- write:(NXTypedStream *) stream
{
  NXWriteTypes( stream, "***i", &description, &startTimeString,
	       &startDateString, &minutes );
  return self;
}

@end
