//
//  LostClient.m
//  NG911
//
//  Created by Rachid Jeitani on 10/30/11.
//  Copyright (c) 2011 Columbia University All rights reserved.
//

#import "LostClient.h"


@interface LostClient()

// private API, use the public method lostRequestWithLatitute:Longitude: to get the response of the LoST request
- (NSString *)outgoingXMLwithLatitude:(double) latitude longitude:(double) longitude;
- (void)performLostHTTPRequest:(NSString *) xml;
- (bool)parseXML:(NSString *) xml;

@end

@implementation LostClient

@synthesize dnsServer, serverName, uri, currentStringValue, returnedXML;


-(NSString *) outgoingXMLwithLatitude:(double)latitude longitude:(double)longitude{
    
    NSLog(@"Outgoing XML With Latitude");
    NSString *lat = [NSString stringWithFormat:@"%f", latitude];
    NSString *longt = [NSString stringWithFormat:@"%f", longitude];
  
    NSString *encodedXML = @"<?xml version='1.0' encoding='UTF-8'?>";
    
    encodedXML = [encodedXML stringByAppendingString:@"<findService "];
    encodedXML = [encodedXML stringByAppendingString:@"xmlns='urn:ietf:params:xml:ns:lost1' "];
    encodedXML = [encodedXML stringByAppendingString:@"xmlns:p2='http://www.opengis.net/gml' "];
    encodedXML = [encodedXML stringByAppendingString:@"serviceBoundary='reference' "];
    encodedXML = [encodedXML stringByAppendingString:@"recursive='true'>"];
    encodedXML = [encodedXML stringByAppendingString:@"<location id='identifier' "];
    encodedXML = [encodedXML stringByAppendingString:@"profile='geodetic-2d'>"];
    encodedXML = [encodedXML stringByAppendingString:@"<p2:Point id='point1' "];
    encodedXML = [encodedXML stringByAppendingString:@"srsName='urn:ogc:def:crs:EPSG::4326'>"];
    encodedXML = [encodedXML stringByAppendingString:@"<p2:pos>"];
    encodedXML = [encodedXML stringByAppendingString:lat];
    encodedXML = [encodedXML stringByAppendingFormat:@" %@</p2:pos>", longt];
    encodedXML = [encodedXML stringByAppendingString:@"</p2:Point>"];
    encodedXML = [encodedXML stringByAppendingString:@"</location>"];
    encodedXML = [encodedXML stringByAppendingString:@"<service>urn:service:sos.police</service>"];
    encodedXML = [encodedXML stringByAppendingString:@"</findService>"];
    
    return encodedXML;
    
}


-(NSString *) lostRequestWithLatitude:(double)latitude longitude:(double)longitude {

    NSLog(@"LostRequestWithLatitude");
    // get xml request
    
    NSString *xml = [self outgoingXMLwithLatitude:latitude longitude:longitude];
    [self performLostHTTPRequest:xml];

    if (returnedXML != nil){
        // parse the XML
        bool success = [self parseXML:returnedXML];
        if (success){
            return uri;
        }
    }

    return uri;
}


-(void) performLostHTTPRequest:(NSString *)xml{
    
    NSLog(@"PerformLostHTTPRequest");
    if (serverName == nil) {
        serverName = @"http://ng911-lost1.cs.columbia.edu:8080/lost/LoSTServlet";
    }

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:serverName]];
    [request setHTTPMethod:@"POST"];
    
    // set header
    
    NSString *contentType = [NSString stringWithFormat:@"text/xml"];
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];
    
    // body
    
    NSMutableData *postBody = [NSMutableData data];
    [postBody appendData:[xml dataUsingEncoding:NSUTF8StringEncoding]];
    
    // post
    [request setHTTPBody:postBody];
    
    // get response
    
    NSHTTPURLResponse * urlResponse = nil;
    NSError *error = [[NSError alloc] init];
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"Response Code: %d", [urlResponse statusCode]);
    
    returnedXML = [NSString stringWithString:result];
    [error release];
    [result release];
}

-(bool) parseXML:(NSString *)xml {
    NSLog(@"ParseXML");
    bool success; 
    
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:[xml dataUsingEncoding:NSUTF8StringEncoding]];

    [parser setDelegate:self];
    [parser setShouldResolveExternalEntities:YES];
    success = [parser parse];
    [[[(AppDelegate *)[[UIApplication sharedApplication] delegate] loading] view] removeFromSuperview];
    
    [parser release];
    return success;
}



-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
    
    
    if ([elementName isEqualToString:@"uri"]) {
        
        uri = [[NSString alloc] init];
        return;
    }
    
    
}

-(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {

    if (!currentStringValue) {
        currentStringValue = [[NSMutableString alloc] initWithString:string];
    } else {
     [currentStringValue appendString:string];   
    }
    
}


-(void) parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
    
    if ([elementName isEqualToString:@"uri"]) {
        if (currentStringValue) {
            
         uri = [NSString stringWithString:currentStringValue];
         return;
        }

    }
    
    [currentStringValue release];
    currentStringValue = nil;
    
}


-(void) dealloc {

    serverName = nil;
    dnsServer = nil;
    uri = nil;
    currentStringValue = nil;
    returnedXML = nil;
    
    [super dealloc];
    
}

@end
