/*
 * AppController.j
 *
 * Created by Philippe Laval on 2009/03/06.
 * Copyright 2009 Philippe Laval. All rights reserved.
 */

/* http://cappuccino.org/learn/tutorials/objective-j-tutorial.php */

@import <Foundation/CPObject.j>


@implementation AppController : CPObject
{
	CPTextField label;
	CPWebView webView;
}

- (void)applicationDidFinishLaunching:(CPNotification)aNotification
{
	/* http://localhost/MyApp/#debug */
	CPLogRegister(CPLogPopup)

    var theWindow = [[CPWindow alloc] initWithContentRect:CGRectMakeZero() styleMask:CPBorderlessBridgeWindowMask];
    var contentView = [theWindow contentView];

	[self addTabViewToContentView:contentView];
	


    [theWindow orderFront:self];

    // Uncomment the following line to turn on the standard menu bar.
    [self setupMenu];
    
	/* debugger; */
    
    /*
	CPLog("a message");
	CPLog.error("an error");
	CPLog.debug("a debug message");
	*/	
}


-(void) addOtherViewsToContentView:(CPView)contentView
{
    label = [[CPTextField alloc] initWithFrame:CGRectMakeZero()];
    [label setStringValue:@"Hello World!"];
    [label setFont:[CPFont systemFontOfSize:24.0]];
    [label setFont:[CPFont boldSystemFontOfSize:24.0]];
    [label setFont:[CPFont fontWithName:@"Courier" size:24.0]];
    [label setFont:[CPFont boldFontWithName:@"Courier" size:24.0]];
    [label sizeToFit];
    // [label setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin];
	//    [label setFrameOrigin:CGPointMake((CGRectGetWidth([contentView bounds]) - CGRectGetWidth([label frame])) / 2.0, (CGRectGetHeight([contentView bounds]) - CGRectGetHeight([label frame])) / 2.0)];
	[label setFrameOrigin:CGPointMake(400, 200)];

    [contentView addSubview:label];


	var button = [[CPButton alloc] initWithFrame:CGRectMake(10, 120, 200, 24)];
//	[button setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin];
	[button setTitle:"Show an alert"];
	[button setTarget:self];
	[button setAction:@selector(showAlert:)];                
				  
	[contentView addSubview:button];

	[self addWebViewToContentView:contentView];
	[self addNavigationButtonsToContentView:contentView];

	[self addColorPanelButtonToContentView:contentView];
	[self addSegmentedControlToContentView:contentView];
}


-(void)playWithFonts:(id)sender
{
	debugger;

	var sharedFontManager = [CPFontManager sharedFontManager];
	var availableFonts = [sharedFontManager availableFonts];
	
	var font = nil;
	var enumerator = [availableFonts objectEnumerator];
    while (font = [enumerator nextObject])
	{
		CPLog.warn(font);	
		// CPLog.warn([font cssString]);	
		// CPLog.warn([font familyName]);	
	}
}

-(void) setupMenu
{
  	var menu = [[CPMenu alloc] initWithTitle:@"dummy"];
  	
  	var menuItem1 = [[CPMenuItem alloc] initWithTitle:@"File" action:nil keyEquivalent:@"1"];
  	
  	[menu addItem:menuItem1];
  	 	

  	var menu11 = [[CPMenu alloc] initWithTitle:@"dummy"];
  	var menuItem111 = [[CPMenuItem alloc] initWithTitle:@"AAA" action:@selector(showAlert:) keyEquivalent:@"3"];
  	[menu11 addItem:menuItem111];
  	[menu11 addItem:[CPMenuItem separatorItem]];
  	var menuItem112 = [[CPMenuItem alloc] initWithTitle:@"BBB" action:@selector(showAlert:) keyEquivalent:@"3"];
  	[menu11 addItem:menuItem112];


	[menuItem1 setSubmenu:menu11];


  	var menuItem2 = [[CPMenuItem alloc] initWithTitle:@"Edit" action:nil keyEquivalent:@"4"];
  	[menu addItem:menuItem2];


  	var menu2 = [[CPMenu alloc] initWithTitle:@"dummy"];
  	var menuItem3 = [[CPMenuItem alloc] initWithTitle:@"CCC" action:@selector(showAlert:) keyEquivalent:@"3"];
  	[menu2 addItem:menuItem3];
  	[menu2 addItem:[CPMenuItem separatorItem]];
  	
  	var menuItem4 = [[CPMenuItem alloc] initWithTitle:@"DDD" action:nil keyEquivalent:@"2"];
  	[menu2 addItem:menuItem4];
	[menu2 addItem:[[CPMenuItem alloc] initWithTitle:@"EEE" action:nil keyEquivalent:@"2"]];

  	var menu3 = [[CPMenu alloc] initWithTitle:@"Phil"];
  	[menu3 addItem:[[CPMenuItem alloc] initWithTitle:@"GGG" action:@selector(showAlert:) keyEquivalent:@"2"]];
	[menuItem4 setSubmenu:menu3];


	[menuItem2 setSubmenu:menu2];
  	 	
	var sharedApplication = [CPApplication sharedApplication];
	[sharedApplication setMainMenu:menu];

	// Show the application menu
	[CPMenu setMenuBarVisible:YES];
}


-(void) addSecureTextFieldToContentView:(CPView)contentView
{
	var secureTextField = [[CPSecureTextField alloc] initWithFrame: CGRectMake(10, 60, 200, 24)];
	[secureTextField setStringValue:@"password"];
	[secureTextField setEditable:YES];
	[secureTextField setSelectable:YES];
	[secureTextField setBezeled:YES];
	[secureTextField setBezeled:YES];
	[secureTextField setBordered:YES]
	
	[secureTextField sizeToFit];

	[contentView addSubview:secureTextField];
	var password = [secureTextField stringValue];
}

-(void) addColorWellToContentView:(CPView)contentView
{
	var colorWell = [[CPColorWell alloc] initWithFrame: CGRectMake(10, 10, 40, 40)];
	[colorWell setBordered:YES];
	[contentView addSubview:colorWell];
}

-(void) addSegmentedControlToContentView:(CPView)contentView
{

	var segmentedControl = [[CPSegmentedControl alloc] initWithFrame: CGRectMake(10, 80, 200, 24)];
	[segmentedControl setSegmentCount:2];
	[segmentedControl setWidth:50 forSegment:0];
	
	[segmentedControl setLabel:@"AAA" forSegment:0];
	[segmentedControl setLabel:@"BBB" forSegment:1];
	

	[contentView addSubview:segmentedControl];

	
	
	var menu0 = [[CPMenu alloc] initWithTitle:@"dummy"];
	[menu0 addItem:[[CPMenuItem alloc] initWithTitle:@"ZZZ" action:nil keyEquivalent:@"2"]];

	[segmentedControl setMenu:menu0 forSegment:0];	

	var menu1 = [[CPMenu alloc] initWithTitle:@"dummy"];
	[menu1 addItem:[[CPMenuItem alloc] initWithTitle:@"XXX" action:nil keyEquivalent:@"2"]];
	
	[segmentedControl setMenu:menu1 forSegment:1];	


	var button = [[CPPopUpButton alloc] initWithFrame:CGRectMake(20, 200, 200, 24) pullsDown:NO];
	[button addItemWithTitle:@"AAA"];
	[button addItemWithTitle:@"BBB"];

//    [button sizeToFit];

	[contentView addSubview:button];

	
	var button = [[CPPopUpButton alloc] initWithFrame:CGRectMake(20, 250, 200, 24) pullsDown:YES];
	[button addItemWithTitle:@"Choose an action:"];
	[button addItemWithTitle:@"Start Listening"];
	[button addItemWithTitle:@"Stop Listening"];
	[button addItemWithTitle:@"Generate Notifications"];
	[button addItemWithTitle:@"Play with fonts"];
	[button addItemWithTitle:@"Play with bundle"];

	var menuItem = [button itemAtIndex:1];
	[menuItem setTarget:self];
	[menuItem setAction:@selector(startListening:)];
	
	var menuItem = [button itemAtIndex:2];
	[menuItem setTarget:self];
	[menuItem setAction:@selector(stopListening:)];

	var menuItem = [button itemAtIndex:3];
	[menuItem setTarget:self];
	[menuItem setAction:@selector(playWithUserSessionManager:)];

	var menuItem = [button itemAtIndex:4];
	[menuItem setTarget:self];
	[menuItem setAction:@selector(playWithFonts:)];

	var menuItem = [button itemAtIndex:5];
	[menuItem setTarget:self];
	[menuItem setAction:@selector(playWithBundle:)];

	
//    [button sizeToFit];

	[contentView addSubview:button];

}

-(void) startListening:(id)sender
{
	CPLog.trace(@"startListening");
	
	var defaultCenter = [CPNotificationCenter defaultCenter];
    
    [defaultCenter addObserver:self selector:@selector(handleSession:)
						name:CPUserSessionManagerStatusDidChangeNotification
						object:[CPUserSessionManager defaultManager]];
						
    [defaultCenter addObserver:self selector:@selector(handleSession:)
						name:CPUserSessionManagerUserIdentifierDidChangeNotification
						object:[CPUserSessionManager defaultManager]];

}

-(void) stopListening:(id)sender
{
	CPLog.trace(@"stopListening");

	var defaultCenter = [CPNotificationCenter defaultCenter];
    

    [defaultCenter removeObserver:self
						name:CPUserSessionManagerStatusDidChangeNotification
						object:[CPUserSessionManager defaultManager]];
						
    [defaultCenter removeObserver:self
						name:CPUserSessionManagerUserIdentifierDidChangeNotification
						object:[CPUserSessionManager defaultManager]];

}


-(void)handleSession:(CPNotification)aNotification
{
	CPLog.trace(@"handleSession");


	debugger;
	
	var name = [aNotification name];
	
	CPLog.trace(name);

	var userSessionManager = [aNotification object];
	var number = [CPNumber numberWithLong:[userSessionManager status]];
	CPLog.trace([number stringValue]);
	CPLog.trace([userSessionManager userIdentifier]);

}

-(void)playWithUserSessionManager:(id)sender
{
	CPLog.trace(@"playWithUserSessionManager");

	var defaultManager = [CPUserSessionManager defaultManager];
	[defaultManager setUserIdentifier:@"Philippe"];
	
	/* CPUserSessionUndeterminedStatus CPUserSessionLoggedInStatus CPUserSessionLoggedOutStatus */
	[defaultManager setStatus:CPUserSessionLoggedInStatus];
}



-(void)playWithBundle:(id)sender
{
	debugger;

	var mainBundle = [CPBundle mainBundle];
	var path = [mainBundle bundlePath];
	var resourcePath = [mainBundle resourcePath];

	// cause a problem
	//CPLog.trace(path);
	CPLog.trace(resourcePath);
	
	var path = [mainBundle pathForResource:"test.jpg"];
	CPLog.trace(path);
	
	var infoDictionary = [mainBundle infoDictionary];
	
	CPLog.trace([infoDictionary objectForKey:@"CPApplicationDelegateClass"]);
	CPLog.trace([infoDictionary objectForKey:@"CPBundleName"]);
	CPLog.trace([infoDictionary objectForKey:@"CPPrincipalClass"]);

}


-(void) addTabViewToContentView:(CPView)contentView
{
	var tabView = [[CPTabView alloc] initWithFrame: CGRectMake(
					10,
					10,
					CGRectGetWidth([contentView bounds]) - 20, CGRectGetHeight([contentView bounds]) - 20
				 )];


	[tabView setTabViewType:CPTopTabsBezelBorder];

/* CPViewMinXMargin CPViewMaxXMargin */
	[tabView setAutoresizingMask: CPViewWidthSizable | CPViewHeightSizable];

	[contentView addSubview:tabView];
								
	var tabViewItem1 = [[CPTabViewItem alloc] initWithIdentifier:@"tabViewItem1"];
	[tabViewItem1 setLabel:@"First Tab"];
	
	var view1 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 100, 100)];
	
	var button = [[CPButton alloc] initWithFrame: CGRectMake(10, 10, 150, 24)];
	[button setTitle:"view1"];
	[button setTarget:self];
	[button setAction:@selector(showAlert:)];                
				  
	[view1 addSubview:button];


	[tabViewItem1 setView:view1];
	var auxiliaryView1 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 50, 50)];
	
	button = [[CPButton alloc] initWithFrame: CGRectMake(10, 10, 150, 24)];
	[button setTitle:"auxiliaryView1"];
	[button setTarget:self];
	[button setAction:@selector(showAlert:)];                
				  
	[auxiliaryView1 addSubview:button];


	[tabViewItem1 setAuxiliaryView:auxiliaryView1];
	
	var tabViewItem2 = [[CPTabViewItem alloc] initWithIdentifier:@"tabViewItem2"];
	[tabViewItem2 setLabel:@"Second Tab"];

	var view2 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 50, 50)];
	[tabViewItem2 setView:view2];
	var auxiliaryView2 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 50, 50)];
	[tabViewItem2 setAuxiliaryView:auxiliaryView2];

	[self addColorWellToContentView:view2];
	[self addSecureTextFieldToContentView:view2];


	var tabViewItem3 = [[CPTabViewItem alloc] initWithIdentifier:@"tabViewItem3"];
	[tabViewItem3 setLabel:@"Text Fields"];

	var view3 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 50, 50)];
	[tabViewItem3 setView:view3];
	var auxiliaryView3 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 50, 50)];
	[tabViewItem3 setAuxiliaryView:auxiliaryView3];

	[self addTextFieldsToContentView:view3];

	var tabViewItem4 = [[CPTabViewItem alloc] initWithIdentifier:@"tabViewItem4"];
	[tabViewItem4 setLabel:@"Other"];

	var view4 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 50, 50)];
	[tabViewItem4 setView:view4];
	var auxiliaryView4 = [[CPView alloc] initWithFrame: CGRectMake(0, 0, 50, 50)];
	[tabViewItem4 setAuxiliaryView:auxiliaryView4];

	[self addOtherViewsToContentView:view4];

	[tabView addTabViewItem:tabViewItem1];
	[tabView addTabViewItem:tabViewItem2];
	[tabView addTabViewItem:tabViewItem3];
	[tabView addTabViewItem:tabViewItem4];
	
	[tabView selectFirstTabViewItem:self];

}

-(void) addTextFieldsToContentView:(CPView)contentView
{
	var secureTextField = [[CPSecureTextField alloc] initWithFrame: CGRectMake(10, 80, 200, 24)];
	[secureTextField setStringValue:@"a very long password to test the sizeToFit"];
	[secureTextField setEditable:YES];
	[secureTextField setSelectable:YES];
	[secureTextField setBezeled:YES];
	[secureTextField setBezelStyle:CPTextFieldSquareBezel];
	[secureTextField setBordered:NO]
	[secureTextField sizeToFit];
	[contentView addSubview:secureTextField];

	var textField = [[CPTextField alloc] initWithFrame: CGRectMake(10, 10, 200, 24)];
	[textField setStringValue:@"a very long text to test the sizeToFit"];
	[textField setEditable:YES];
	[textField setSelectable:YES];
	[textField setBezeled:YES];
	[textField setBezelStyle:CPTextFieldRoundedBezel];
	[textField setBordered:YES]
	[textField sizeToFit];
	[contentView addSubview:textField];

	textField = [[CPTextField alloc] initWithFrame: CGRectMake(10, 50, 200, 24)];
	[textField setStringValue:@"a very long text to test the sizeToFit"];
	[textField setEditable:YES];
	[textField setSelectable:YES];
	[textField setBezeled:YES];
	[textField setBezelStyle:CPTextFieldSquareBezel];
	[textField setBordered:YES]
	[textField sizeToFit];
	[contentView addSubview:textField];

	textField = [[CPTextField alloc] initWithFrame: CGRectMake(300, 10, 200, 24)];
	[textField setStringValue:@"a very long text to test the sizeToFit"];
	[textField setEditable:YES];
	[textField setSelectable:YES];
	[textField setBezeled:YES];
	[textField setBezelStyle:CPTextFieldRoundedBezel];
	[textField setBordered:NO]
	[textField sizeToFit];
	[contentView addSubview:textField];

	textField = [[CPTextField alloc] initWithFrame: CGRectMake(300, 50, 200, 24)];
	[textField setStringValue:@"a very long text to test the sizeToFit"];
	[textField setEditable:YES];
	[textField setSelectable:YES];
	[textField setBezeled:YES];
	[textField setBezelStyle:CPTextFieldSquareBezel];
	[textField setBordered:NO]
	[textField sizeToFit];
	[contentView addSubview:textField];

	textField = [[CPTextField alloc] initWithFrame: CGRectMake(600, 10, 200, 24)];
	[textField setStringValue:@"a very long text to test the sizeToFit"];
	[textField setEditable:YES];
	[textField setSelectable:YES];
	[textField setBezeled:NO];
	[textField setBezelStyle:CPTextFieldRoundedBezel];
	[textField setBordered:YES]
	[textField sizeToFit];
	[contentView addSubview:textField];

	textField = [[CPTextField alloc] initWithFrame: CGRectMake(600, 50, 200, 24)];
	[textField setStringValue:@"a very long text to test the sizeToFit"];
	[textField setEditable:YES];
	[textField setSelectable:YES];
	[textField setBezeled:NO];
	[textField setBezelStyle:CPTextFieldSquareBezel];
	[textField setBordered:YES]
	[textField sizeToFit];
	[contentView addSubview:textField];
}

-(void) addNavigationButtonsToContentView:(CPView)contentView
{
	var backButton = [[CPButton alloc] initWithFrame: CGRectMake(100, 20, 80, 24)];
							  
	[backButton setTitle:"Back"];
	
	[backButton setTarget:webView];
	[backButton setAction:@selector(goBack:)];                
				  
	[contentView addSubview:backButton];


	var forwardButton = [[CPButton alloc] initWithFrame: CGRectMake(200, 20, 80, 24)];
							  
	[forwardButton setTitle:"Forward"];
	
	[forwardButton setTarget:webView];
	[forwardButton setAction:@selector(goForward:)];                
				  
	[contentView addSubview:forwardButton];

	var printButton = [[CPButton alloc] initWithFrame: CGRectMake(300, 20, 80, 24)];
							  
	[printButton setTitle:"Print"];
	
	[printButton setTarget:webView];
	[printButton setAction:@selector(print:)];                
				  
	[contentView addSubview:printButton];

	var stopButton = [[CPButton alloc] initWithFrame: CGRectMake(400, 20, 80, 24)];
							  
	[stopButton setTitle:"Stop"];
	
	[stopButton setTarget:webView];
	[stopButton setAction:@selector(stopLoading:)];                
				  
	[contentView addSubview:stopButton];

}



-(void) addWebViewToContentView:(CPView)contentView
{
	webView = [[CPWebView alloc] initWithFrame: CGRectMake(
					10,
					100,
					CGRectGetWidth([contentView bounds]) - 20, 200
				 )];

/* CPViewMinXMargin CPViewMaxXMargin */
	[webView setAutoresizingMask: CPViewWidthSizable |
								CPViewMinYMargin | CPViewMaxYMargin];
								
	// [webView setDrawsBackground:YES];

	[contentView addSubview:webView];
}


-(void) addColorPanelButtonToContentView:(CPView)contentView
{
	var button = [[CPButton alloc] initWithFrame: CGRectMake(20, 150, 150, 24)];
				
	[button setTitle:"Show the Color Panel"];
//	[button sizeToFit];
				
//	[button setAutoresizingMask:CPViewMinXMargin | CPViewMaxXMargin | CPViewMinYMargin | CPViewMaxYMargin];
	
	
	[button setTarget:self];
	[button setAction:@selector(showColorPanel:)];                
				  
	[contentView addSubview:button];
}


- (void)showColorPanel:(id)sender
{
	var sharedColorPanel = [CPColorPanel sharedColorPanel];
	[CPColorPanel setPickerMode:CPSliderColorPickerMode];
	    
	// Bug in 0.7beta : we have to setup a color
	[sharedColorPanel setColor:[CPColor blueColor]];
    [sharedColorPanel orderFront:self];
}


- (void)showAlert:(id)sender
{
	var alert = [[CPAlert alloc] init];
	[alert setMessageText:@"My new alert"];
	[alert setDelegate:self];
	[alert setAlertStyle:CPWarningAlertStyle];
	[alert addButtonWithTitle:@"OK"]
	[alert addButtonWithTitle:@"Cancel"]
	[alert runModal];
}

-(void)alertDidEnd:(CPAlert)theAlert returnCode:(int)returnCode
{
	if (returnCode == 0)
	{
		[label setStringValue:@"OK !"];
		
		[webView setMainFrameURL:@"http://cappuccino.org/"];
	}
	else if (returnCode == 1)
	{
		[label setStringValue:@"Cancel !"];
		// [webView setMainFrameURL:@"http://www.nice-panorama.com/"];
		
		[self sendSynchronousRequest];
	}

}

/*
+ (CPString)JSONFromObject:(JSObject)anObject
- (JSObject)objectFromJSON
*/

-(void)sendSynchronousRequest
{
	var request = [CPURLRequest requestWithURL:"http://macbookpro.local/"];
	var response;
	var error;

	debugger;
	
	// For now response and error are not used
	var data = [CPURLConnection sendSynchronousRequest:request returningResponse:response error:error];
	/*
	if ([response statusCode] == 200)
	{
		var text = [data string];
		
		console.log([data string]);
		
		CPLog.warn(text);
		CPLog.trace(text);
	}
	*/
	if (data != nil)
	{
		var text = [data string];
		
		console.log([data string]);
		
		CPLog.trace(text);
	}
	
}


@end
