/*
 *  You may freely copy, distribute and reuse the code in this example.
 *  This code manages the windows for TemplateApp
 */

#import "TemplateApp.h"
#import "TemplateView.h"

#import <libc.h>
#import <appkit/Control.h>
#import <appkit/TextField.h>
#import <appkit/Window.h>

@implementation TemplateApp

+ new
{
    self = [super new];
    [self setDelegate:self];	// For appDidHide:
    return self;
}
   
// appDidInit is called as the first thing in the run loop of the 
// application. At this point, everything is created, but we haven't entered
// the event loop yet. appDidInit initializes a few things and
// calls the gotoFirstLevel: method of the BreakView instance to get
// started on a new game.

- appDidInit:app 
{
    [game gotoFirstLevel:self];
    [controlWindow removeFromEventMask:NX_KEYDOWNMASK|NX_KEYUPMASK];
    [controlWindow orderFront:self];
    [gameWindow setDelegate:self];  // We want window resized messages
    [gameWindow makeKeyAndOrderFront:self];
    [gameWindow addToEventMask:NX_KEYDOWNMASK|NX_KEYUPMASK];
    [gameWindow makeFirstResponder:game];
    return self;
}

// appDidHide is called when the application is hidden. It doesn't
// make sense to run the game while the application is running, also,
// in case the boss walks by you want to be able to hit just Command-h and
// have the game hide and pause at the same time. This way the boss won't
// ask where "ping-ping" noises are coming from and you will not have lost
// a high-score game.

- appDidHide:app
{
   [game stop:self];
   return self;
}

// We do pretty much the same if the user miniaturizes the game window.

- windowDidMiniaturize:window
{
   if (window == gameWindow) [game stop:self];
   return self;
}

// Constrain window resizing. The following values are somewhat arbitrary;
// they need to depend on the window style, and the actual size of the view
// within the window. 

#define MINWIDTH  (GAMEWIDTH * 0.9)
#define MINHEIGHT (GAMEHEIGHT * 0.9)

- windowWillResize:window toSize:(NXSize *)sz
{
    if (window == gameWindow) {
	if (sz->width  < MINWIDTH)  sz->width = MINWIDTH;
	if (sz->height < MINHEIGHT) sz->height = MINHEIGHT;
    }
    return self;
}   

// printGame: allows us to print the game window. We could've just connected
// the "Print..." menu item to the window's smartPrintPSCode:; however, we
// wanted to be able to change the title to reflect the status.

- printGame:sender
{
    char *savedTitle = NXCopyStringBuffer([gameWindow title]);
    char statusString[100];

    sprintf (statusString, "Score: %d  Level: %d", [game score], [game level]);
    [gameWindow setTitle:statusString];
    [gameWindow smartPrintPSCode:sender];
    [gameWindow setTitle:savedTitle];
    free (savedTitle);

    return self;
}


// Method to load the .nib file for the info panel.

- showInfo:sender
{
    if (!infoPanel) {
	[self loadNibSection:"Info.nib" owner:self withNames:NO];
    }
    [infoPanel makeKeyAndOrderFront:sender];
    return self;
}


@end
