#import "ColeSlaw.h"

#import "ScaledViewPart.h"
#import "DesquamateViewPart.h"
#import "PolyFrogViewPart.h"
#import "FooFaraw.h"

#import <appkit/Window.h>
#import <appkit/View.h>
#import <appkit/graphics.h>
#import <appkit/Application.h>
#import <appkit/Matrix.h>

@implementation ColeSlaw
- init
{
  [super init];
  inited=NO;
  return self;
}

- doFirstInit
{
  NXRect bowlSize;
  ginsuView=[saladBowl contentView];
  [ginsuView getBounds:&bowlSize];
  redLettuce=[[ScaledView alloc] initFrame:&bowlSize];
  greenPeppers=[[PolyFrogView alloc] initFrame:&bowlSize];
  [ginsuView setAutoresizeSubviews:YES];
  [ginsuView setAutosizing:NX_WIDTHSIZABLE | NX_HEIGHTSIZABLE];

  // Sam''s majic window code
  [saladBowl useOptimizedDrawing:YES];
  [saladBowl setOneShot:YES];
  [saladBowl setDelegate:self];
  [saladBowl setBackgroundGray:NX_BLACK];

  inited=YES;

  return self;
}

- windowDidResize:sender
{
  NXRect aRect;
  
  [ginsuView getFrame:&aRect];
  aRect.origin.x=0.0;
  aRect.origin.y=0.0;
  [redLettuce setFrame:&aRect];
  [greenPeppers setFrame:&aRect];
  return self;
}  

- advancePhase
{
  int eMask=NX_ALLEVENTS;
  NXEvent anEvent,*theEvent;
  
  [ginsuView lockFocus];
  do {
    [[redLettuce oneStep] oneStep];
    [[greenPeppers oneStep] oneStep];

    if([NXApp peekNextEvent:NX_FLAGSCHANGEDMASK
	into:&anEvent]){
      theEvent=[NXApp getNextEvent:NX_FLAGSCHANGEDMASK];
      if(theEvent->flags & NX_COMMANDMASK) {
	if([redLettuce respondsTo:@selector(commandKey)]){
	  [redLettuce commandKey];
	}
	if([greenPeppers respondsTo:@selector(commandKey)]){
	  [greenPeppers commandKey];
	}
      } else if (theEvent->flags & NX_ALTERNATEMASK) {
	if([redLettuce respondsTo:@selector(alternateKey)]){
	  [redLettuce alternateKey];
	}
	if([greenPeppers respondsTo:@selector(alternateKey)]){
	  [greenPeppers alternateKey];
	}

      }else noDiversions = NO;
    }
    
    noDiversions= noDiversions ? ([NXApp
				   peekNextEvent:eMask into:&anEvent
				   waitFor:0.0
				   threshold:NX_BASETHRESHOLD]==NULL) : NO;
  } while (cuisanartOn && noDiversions);
  [ginsuView unlockFocus];
  
  return self;
}

void phase_advance(DPSTimedEntry teNumber, double now,void *theColeSlaw)
{
  [(id) theColeSlaw advancePhase];
}

- startShredder:sender
{
  if (!inited) [self doFirstInit];
  if (!cuisanartOn){
    NXRect bounds;
    [[sender selectedCell] setTitle:"noShred"];
    cuisanartOn=YES;
    [ginsuView lockFocus];
    NXSetColor(NX_COLORBLACK);
    [ginsuView getBounds:&bounds];
    NXRectFill(&bounds);
    [saladBowl flushWindow];
    [ginsuView unlockFocus];
    motor=DPSAddTimedEntry(0.02, &phase_advance,self,
			   NX_BASETHRESHOLD);
  } else {
    [[sender selectedCell] setTitle:"Shred"];
    cuisanartOn=NO;
    DPSRemoveTimedEntry(motor);
  }
  
  return self;
}
@end



