/*
 * 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>

@import <Foundation/CPPropertyListSerialization.j>

@import "Person.j"


// This is needed in Cappucinno 0.6 and will be incorporated in next release
@implementation CPString (JSON)
 
// Returns a string representing the supplied JavaScript object encoded as JSON.
+ (CPString)JSONFromObject:(JSObject)anObject
{
    return CPJSObjectCreateJSON(anObject);
}
 
// Returns a JavaScript object decoded from the string's JSON representation.
- (JSObject)objectFromJSON
{
    return CPJSObjectCreateWithJSON(self);
}
 
@end



@implementation AppController : CPObject
{
	CPURLConnection urlConnection;
}

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

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



	var button = [[CPButton alloc] initWithFrame: CGRectMake(20, 20, 200, 24)];
							  
	[button setAutoresizingMask:CPViewMinXMargin | 
								CPViewMaxXMargin | 
								CPViewMinYMargin | 
								CPViewMaxYMargin];
	
	[button setTitle:"CPKeyedArchiver"];
	// Cappuccino 0.6 : bug on Safari, the button look weird when using sizeToFit
	//[button sizeToFit];
	
	[button setTarget:self];
	[button setAction:@selector(testKeyedArchiver:)];                
				  
	[contentView addSubview:button];


	button = [[CPButton alloc] initWithFrame: CGRectMake(20, 50, 200, 24)];
							  
	[button setAutoresizingMask:CPViewMinXMargin | 
								CPViewMaxXMargin | 
								CPViewMinYMargin | 
								CPViewMaxYMargin];
	
	[button setTitle:"CPPropertyListSerialization"];
	//[button sizeToFit];

	[button setTarget:self];
	[button setAction:@selector(testPropertyListSerialization:)];                
				  
	[contentView addSubview:button];


	button = [[CPButton alloc] initWithFrame: CGRectMake(20, 80, 200, 24)];
							  
	[button setAutoresizingMask:CPViewMinXMargin | 
								CPViewMaxXMargin | 
								CPViewMinYMargin | 
								CPViewMaxYMargin];
	
	[button setTitle:"JSON"];
	//[button sizeToFit];

	[button setTarget:self];
	[button setAction:@selector(testJSON:)];                
				  
	[contentView addSubview:button];

    [theWindow orderFront:self];
}

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

/*
	Reference site about JSON notation
	http://www.json.org/
	
	http://www.hunlock.com/blogs/Mastering_JSON_(_JavaScript_Object_Notation_)
	http://www.alsacreations.com/tuto/lire/562-bonnes-pratiques-javascript.html

{ 
  "menu": "File", 
  "commands": [ 
      {
          "title": "New", 
          "action":"CreateDoc"
      }, 
      {
          "title": "Open", 
          "action": "OpenDoc"
      }, 
      {
          "title": "Close",
          "action": "CloseDoc"
      }
   ] 
}
*/

	// This is some JSON content in a CPString
	var jsonString = @"{\"menu\": \"File\", \"commands\": [ { \"title\": \"New\", \"action\":\"CreateDoc\" }, { \"title\": \"Open\", \"action\": \"OpenDoc\" }, { \"title\": \"Close\", \"action\": \"CloseDoc\" } ] }";
	CPLog.trace(@"jsonString: " + [jsonString description]);
	
	// Create a javascript object from the JSON content
	var jsObject = [jsonString objectFromJSON];
	
	// Acess to the content of the object
	var menu = jsObject.menu;
	var menu_otherway = jsObject["menu"];
	var firstTitle = jsObject.commands[0].title;
	var firstAction = jsObject.commands[0].action;

	// Create a javascript object from scratch
	var myFirstJSONObject = { "firstName" : "John",
                    "lastName"  : "Doe",
                    "age"       : 23,
                    "tangoDancer"	: true,
                    "rich"	: false,
                    // "bankAccountInSwitzerland" : null generates an error in JSONFromObject
                    "bankAccountInSwitzerland" : "None"}; // null
      
    // Add some other properties to the object
    myFirstJSONObject.isFrench = false;
    myFirstJSONObject.favoriteNumbers = [10, 3, 1968];
    myFirstJSONObject["isAmerican"] = true;
    
      // null is NOT accepted
      // TypeError: Result of expression '_14' [null] is not an object.

	// Get the JSON representation of the object
	var text = [CPString JSONFromObject:myFirstJSONObject];
	CPLog.trace(@"text: " + [text description]);

/*
<CPString 0x0001a8 "{"firstName":"John","lastName":"Doe","age":23,"tangoDancer":true,"rich":false,
"bankAccountInSwitzerland":"None","isFrench":false,"isAmerican":true}">
*/

	// Check for the null in JSON string : it is OK
	jsonString = @"{\"firstName\":\"John\",\"bankAccountInSwitzerland\":null,\"isFrench\":false}";
	jsObject = [jsonString objectFromJSON];

	
	// What to do with a CPValue, is the next question in life.
	var value = [CPValue valueWithJSObject:jsObject];
}


-(void)testKeyedArchiver:(id)sender
{
	debugger;
	
	var philippe = [Person personWithName:@"Laval"];
	[philippe setJobTitle:@"Engineer" company:@"Company name éàç with utf8"];
	
	var data = [CPKeyedArchiver archivedDataWithRootObject:philippe];
		
	CPLog.trace(@"philippe:" + [philippe description]);
	CPLog.trace(@"data: " + [data string]);
	CPLog.trace(@"data: " + [[data plistObject] description]);
		
/*	
2009-02-12 01:09:49.481 Cappuccino [null]: philippe:name: Laval jobTitle: Engineer company: Company name éàç with utf8
2009-02-12 01:09:49.487 Cappuccino [null]: data: 280NPLIST;1.0;D;K;4;$topD;K;4;rootD;K;6;CP$UIDd;1;1E;E;K;8;$objectsA;S;5;$nullD;K;6;$classD;K;6;CP$UIDd;1;2E;K;4;nameD;K;6;CP$UIDd;1;3E;K;8;jobTitleD;K;6;CP$UIDd;1;4E;K;7;companyD;K;6;CP$UIDd;1;5E;E;D;K;10;$classnameS;6;PersonK;8;$classesA;S;6;PersonS;8;CPObjectE;E;S;5;LavalS;8;EngineerS;26;Company name éàç with utf8E;K;9;$archiverS;15;CPKeyedArchiverK;8;$versionS;6;100000E;
2009-02-12 01:09:49.489 Cappuccino [null]: data: CPDictionary {
$version:<CPString 0x0001a1 "100000">
$archiver:<CPString 0x0001a2 "CPKeyedArchiver">
$objects:(<CPString 0x0001a3 "$null">, CPDictionary {
company:CPDictionary {
CP$UID:5
}
jobTitle:CPDictionary {
CP$UID:4
}
name:CPDictionary {
CP$UID:3
}
$class:CPDictionary {
CP$UID:2
}
}, CPDictionary {
$classes:(<CPString 0x0001a4 "Person">, <CPString 0x0001a5 "CPObject">)
$classname:<CPString 0x0001a4 "Person">
}, <CPString 0x00019a "Laval">, <CPString 0x00019c "Engineer">, <CPString 0x00019e "Company name éàç with utf8">)
$top:CPDictionary {
root:CPDictionary {
CP$UID:1
}
}
}
*/

	var objectAsString = [data string];
	var lengthAsInt = [objectAsString length];
	var lengthAsString = [[CPString alloc ] initWithFormat:@"%d", lengthAsInt];


	var newData = [CPData dataWithString:objectAsString];
	var clone = [CPKeyedUnarchiver unarchiveObjectWithData:newData];

	CPLog.trace(@"clone:" + [clone description]);
}

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

	/* sad bug
	var stuff=@"<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\"><plist version=\"1.0\"><dict><key>my_date</key><date>2009-03-15T11:07:07Z</date><key>my_data</key><data></data><key>my_number</key><real>0.9</real><key>my_string</key><string>Hello world</string><key>my_boolean</key><true/><key>my_dict</key><dict><key>key1</key><string>value1</string></dict><key>my_array</key><array><string>test éàç</string><string>test2 $€£</string></array></dict></plist>";
	CPLog.trace(@"data: " + stuff);

	var dataFromStuff = [CPData dataWithString:stuff];	
	var errorString;
	// Problem "date tag not recognized in Plist."
	var dictDeserialized = [CPPropertyListSerialization propertyListFromData:dataFromStuff format:CPPropertyListXMLFormat_v1_0 errorDescription:errorString];
	CPLog.trace(@"dictDeserialized: " + [dictDeserialized description]);
	*/
	

	var keys = [CPArray arrayWithObjects:@"key1", @"key2", @"key3", @"key4", nil];
	var objects = [CPArray arrayWithObjects:@"Some french characters éàç with utf8", 
						[CPNumber numberWithBool:NO], 
						[CPNumber numberWithDouble:9.9], 
						[CPNumber numberWithDouble:8.8], 
						nil];
	var dict = [CPDictionary dictionaryWithObjects:objects forKeys:keys];
	
	var array = [CPArray arrayWithObjects:@"value1", [CPNumber numberWithBool:NO], [CPNull null],
							[CPData dataWithString:@"Cappuccino"],
							[CPDate date], [CPData dataWithString:@"Cappuccino"], nil];

	var errorString;
	var data = [CPPropertyListSerialization dataFromPropertyList:dict format:CPPropertyListXMLFormat_v1_0 errorDescription:errorString];

	CPLog.trace(@"data: " + [data string]);

/*
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version = "1.0">
<dict>
<key>key4</key>
<real>8.8</real>
<key>key3</key>
<real>9.9</real>
<key>key2</key>
<false/>
<key>key1</key>
<string>Some french characters éàç with utf8</string>
</dict>
</plist>
*/

	CPLog.trace(@"data: " + [[data plistObject] description]);

/*
CPDictionary {
key1:<CPString 0x0001af "value1">
key2:false
key3:9.9
key4:8.8
}
*/

	var dict2 = [CPPropertyListSerialization propertyListFromData:data format:CPPropertyListXMLFormat_v1_0 errorDescription:errorString];
	//CPLog.trace(@"dict2: " + [dict2 description]);
	var value1 = [dict2 objectForKey:@"key1"];
	CPLog.trace(@"value1:" + value1);
	
	debugger;
	
	/*
	var data2 = [CPPropertyListSerialization dataFromPropertyList:array format:CPPropertyListXMLFormat_v1_0 errorDescription:errorString];
	CPLog.trace(@"data2: " + [data2 string]);
	*/
	
	/* Result of expression 'keys' [undefined] is not an object.
	[dict setObject:array forKey:@"my_array"];
	data = [CPPropertyListSerialization dataFromPropertyList:dict format:CPPropertyListXMLFormat_v1_0 errorDescription:errorString];
	CPLog.trace(@"data: " + [data string]);
	*/
}

-(void) sendAsynchRequest
{
	request = [[CPURLRequest alloc] initWithURL:@"http://www.your-server.com/services/service1.php"];
	[request setHTTPMethod:@"POST"];
	[request setHTTPBody:@"value"];
	[request setValue:"5" forHTTPHeaderField:@"Content-Length"];
	[request setValue:"text/plain;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
	
	urlConnection = [CPURLConnection connectionWithRequest:request delegate:self];
	[urlConnection start];
}


-(void)connection:(CPURLConnection)connection didFailWithError:(id)error
{
}

-(void)connection:(CPURLConnection)connection didReceiveResponse:(CPHTTPURLResponse)response
{
}

-(void)connection:(CPURLConnection)connection didReceiveData:(CPString)data
{
}

-(void)connectionDidFinishLoading:(CPURLConnection)connection
{
}

-(void)connectionDidReceiveAuthenticationChallenge:(CPURLConnection)connection
{
}


@end
