#import "UpDownView.h"
#import <appkit/appkit.h>

static id font;

@interface UpDownView (PRIVATE)

- (void) _recalcUpTime;

@end 

@implementation UpDownView

- initFrame:(NXRect *)r
{
   [super initFrame: r];
   [self setIsUp: NO];
   [self resetUpTime];
   font = [Font systemFontOfSize: 12 matrix: NX_IDENTITYMATRIX];
   return self;
}

- (BOOL) isUp
{
   return isUp;
}

- (void) setIsUp: (BOOL) aValue since: (time_t) aTime
{
   if(aValue == isUp)
       return;

   isUp = aValue;
   if(isUp)
   {
      [self resetUpTime];
      mark = aTime;
   }
   else
       [self _recalcUpTime];
}

- (void) setIsUp: (BOOL) aValue
{
   [self setIsUp: aValue since: time((time_t *)0)];
}

- (void) resetUpTime
{
   mark = upTime = 0;
}

- (time_t) upTime
{
   return upTime;
}

- drawSelf:(NXRect *)r :(int)count
{
   char buf[15];

   if(!up)
   {
      up = [NXImage findImageNamed: "up"];
      down = [NXImage findImageNamed: "down"];
   }

   PSsetgray(NX_LTGRAY);
   NXRectFill(&bounds);
   [([self isUp]? up : down) composite: NX_SOVER toPoint: &(bounds.origin)];
   if([self isUp])
       [self _recalcUpTime];

   sprintf(buf,"%d:%02d:%02d", upTime / 3600 , (upTime % 3600) / 60, upTime % 60);

   PSsetgray(NX_BLACK);
   [font set];
   PSmoveto(2,2);
   PSshow(buf);

   return self;
}

- windowWillResize:sender toSize:(NXSize *)aSize
{
  static BOOL gotSize=NO;
  static NXSize minSize={ 0, 0};
  if( !gotSize)
    {
      NXRect r;
      [sender getFrame:&r];
      minSize=r.size;
      gotSize=YES;
    }
  aSize->width=MAX( aSize->width, minSize.width);
  aSize->height=MAX( aSize->height, minSize.height);
  return self;
}

@end

@implementation UpDownView (PRIVATE)

- (void) _recalcUpTime
{
   time_t delta, newMark;
      
   delta = (newMark = time((time_t *)0)) - mark;
   mark = newMark;
   upTime += delta;
}


@end 
