//
//  asynchronous post.m
//  melody app
//
//  Created by Odin on 06/10/2016.
//  Copyright © 2016 demain un autre jour. All rights reserved.
//

/*

+---------------------------------------------------------------+
| this is file for asynchronous html post						|
+---------------------------------------------------------------+
 
 */
 
#import "asynchronous post.h"

@implementation asynchronous_post

- (id)init {
	self = [super init];
 
	if(self){
		httpResponse = [[NSMutableArray alloc] init];
	}
 
	return self;
}

// Sends an asynchronous HTTP POST request
- (void)sendRequest:(NSString*)url: (NSString*)body: (NSObject*) sender {
	//NSLog(@"hello w8 for u");
	NSMutableString* requestURL = [[NSMutableString alloc] init];
	[requestURL appendString:url];
 
	NSMutableString* requestBody = [[NSMutableString alloc] init];
	[requestBody appendString:@"request="];
	[requestBody appendString:body];
 
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]];
 
	NSString* requestBodyString = [NSString stringWithString:requestBody];
	NSData *requestData = [NSData dataWithBytes: [requestBodyString UTF8String] length: [requestBodyString length]];
 
	[request setHTTPMethod: @"POST"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
	[request setHTTPBody: requestData];
 
	[[NSURLConnection alloc] initWithRequest:request delegate:sender];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
	[httpResponse setLength:0];
}

// Called when data has been received
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[httpResponse appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
	NSString *responseString = [[[NSString alloc] initWithData:httpResponse encoding:NSUTF8StringEncoding] copy];
 
	//NSLog(@"rsponse is : %@", responseString);
	// Do something with the response
 
	[connection release];
	[httpResponse release];
}

@end
