//
//  ServerComms.m
//  httpPost
//
//  Created by Robert Tubb on 24/02/2013.
//  Copyright (c) 2013 Robert Tubb. All rights reserved.
//

#import "ServerComms.h"
#import "eventLogger.h"

extern EventLogger eventLogger;

@implementation ServerComms
//
-(id)init{
    self = [super init];
    if(self != nil){
        self.requestInProgress = NO;
    }
    return self;
}

//  asynchronous one
-(BOOL)doPostRequest:(NSString *)type withData:(NSString *)data{
    
    if(self.requestInProgress){
        return NO;
    }
    self.currentRequestType = type;
    NSString *localServerURL = @"http://127.0.0.1:8080/testservice/";
    NSString *webServerURL = @"http://www.isophonics.net/datacollector/";

    NSString *urls = [webServerURL stringByAppendingString:type];
    NSURL *url = [NSURL URLWithString:urls];


    // request object
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // the data
    NSString *post = [@"jsontext=" stringByAppendingString:[NSString stringWithFormat:data]];
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
    // length of data
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    
    // request properties/header fields
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData ];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    self.requestInProgress = YES;
    return YES;
    //  asynchronous one??
}
//--------------------------------------------------------------------

// schncronous
-(BOOL)doSyncPostRequest:(NSString *)type withData:(NSString *)data{
    BOOL success;
    
    NSString *localServerURL = @"http://127.0.0.1:8080/testservice/";
    NSString *webServerURL = @"http://www.isophonics.net/datacollector/";
    
    NSString *urls = [webServerURL stringByAppendingString:type];
    NSURL *url = [NSURL URLWithString:urls];
    
    
    // request object
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // the data
    NSString *post = [@"jsontext=" stringByAppendingString:[NSString stringWithFormat:data]];
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
    // length of data
    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
    
    // request properties/header fields
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:postData ];
    
    NSURLResponse* response;
    NSError* error = nil;
    NSData* result = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];
 
    NSString *responseDataString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    
    //NSString* responseDataString = [NSString stringWithUTF8String: ];
    NSLog(@"sync req. data %@", responseDataString);
    [self.data appendData:result];
    
    if([responseDataString isEqualToString:@"testConnection:OK"]){
        
        eventLogger.testConnectionOK();
        success = true;
    }else if([responseDataString isEqualToString:@"questionnaire:OK"]){
        eventLogger.questionnaireOK();
        success = true;
    }else    if([responseDataString isEqualToString:@"eventlog:OK"]){
        // call eventLogger eventlogUploadOK
        eventLogger.eventlogOK();
        success = true;
    }else{
        success = false;
        if([type isEqualToString:@"testConnection"]) eventLogger.testConnectionNotOK();
        if([type isEqualToString:@"eventlog"]) eventLogger.eventlogNotOK();
        if([type isEqualToString:@"questionnaire"]) eventLogger.questionnaireNotOK();
    }
    
    // else check error??
    
    // check result
    self.requestInProgress = NO;
    return success;
}
//-------------------------------------------------------------------------------------------------

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.data setLength:0];
    NSLog(@"didReceiveResponse : %@",response);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)d {
    NSString *responseDataString = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
    
    //NSString* responseDataString = [NSString stringWithUTF8String: ];
    NSLog(@" %@ didRecieveData %@",self.currentRequestType, responseDataString);
    [self.data appendData:d];
    
    if([responseDataString isEqualToString:@"testConnection:OK"]){

        eventLogger.testConnectionOK();
    }else if([responseDataString isEqualToString:@"questionnaire:OK"]){
        eventLogger.questionnaireOK();
    }else    if([responseDataString isEqualToString:@"eventlog:OK"]){
        // call eventLogger eventlogUploadOK
        eventLogger.eventlogOK();
    }else{
        if([self.currentRequestType isEqualToString:@"testConnection"]) eventLogger.testConnectionNotOK();
        if([self.currentRequestType isEqualToString:@"eventlog"]) eventLogger.eventlogNotOK();
        if([self.currentRequestType isEqualToString:@"questionnaire"]) eventLogger.questionnaireNotOK();
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {

    NSLog(@"fail with error");
    if([self.currentRequestType isEqualToString:@"testConnection"]) {
        UIAlertView * av = [ [UIAlertView alloc] initWithTitle:NSLocalizedString(@"Sorry", @"")
                                                       message:[error localizedDescription]
                                                      delegate:nil
                                             cancelButtonTitle:NSLocalizedString(@"OK", @"")
                                             otherButtonTitles:nil ];
        [av show];
        eventLogger.testConnectionNotOK();
        
    }
    if([self.currentRequestType isEqualToString:@"eventlog"]) eventLogger.eventlogNotOK();
    if([self.currentRequestType isEqualToString:@"questionnaire"]) eventLogger.questionnaireNotOK();
    self.requestInProgress = NO;
    // we won't know what kind of request method this was...
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseText = [[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding];
    
    // Do anything you want with it
    NSLog(@"response text: %@",responseText);
    self.requestInProgress = NO;

}

// Handle basic authentication challenge if needed
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    NSString *username = @"username";
    NSString *password = @"password";
    
    NSURLCredential *credential = [NSURLCredential credentialWithUser:username
                                                             password:password
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
/*
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse{
    
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse{
    
}
*/

@end
