//
//  LoginConnection.m
//  VisIVOMobile
//
//  Created by Fabio Vitello on 06/02/12.
//  Copyright 2011 nothing. All rights reserved.
//

#import "LoginConnection.h"
#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"


@implementation LoginConnection

@synthesize receivedData,delegate,delegateMethod,delegateErrorMethod,receivedDictionary;

- (id)initWithReference:(NSString *)anURL username:(NSString *)user password:(NSString *)passwd
{
	if(self = [super init]) {
		myURL = [[NSURL alloc] initWithString:anURL];
		status = [[NSMutableString alloc] initWithString:@""];
		receivedData = [[NSMutableData alloc] init];
        receivedDictionary = [[NSMutableDictionary alloc] init];
		username=user;
		password=passwd;
        
	}	
	return self;
}



- (void)makePostRequest
{

	NSString *post = [[NSString alloc] initWithFormat:@"user=%@&pass=%@&db=lif",username,password];
    
    
	NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];  
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
	_request = [[NSMutableURLRequest alloc] initWithURL:myURL];
	[_request setHTTPMethod:@"POST"];
    [_request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [_request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
	[_request setTimeoutInterval:60.0];
	[_request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
	[_request setHTTPBody:postData];

	if(_request) {
		_connection = [[NSURLConnection alloc] initWithRequest:_request delegate:self];
	}

    
	[post release];
}


#pragma mark NSURLConnection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	if([delegate respondsToSelector:delegateErrorMethod])
		[delegate performSelector:delegateErrorMethod];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	
	NSString *results = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
	
    
	NSData *jsonData = [results dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	    
	NSError *error = nil;
	    
    [receivedDictionary setDictionary:[[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error]];
    
    [results release];
	
	if([delegate respondsToSelector:delegateMethod]) {
		[delegate performSelector:delegateMethod withObject:self];	
	}
}



-(void)dealloc {
	[myURL release];
	[status release];
	[_request release];
	[_connection release];
	[receivedData release];
	[username release];
	[password release];
	[super dealloc];
}
@end


