//
//  MPFindRequest.m
//  VirtualEarthKit
//
//  Created by Colin Cornaby on 11/18/08.
//  Copyright 2008 Consonance Software. All rights reserved.
//

#import "MPFindRequest.h"
#import "VELocationUtilities.h"


@implementation MPFindRequest

@synthesize location = m_location, distance = m_distance, filter = m_filter, datasourceName = m_datasourceName, range = m_range;

-(id)init
{
	self = [super init];
	m_range = NSMakeRange(0, 25);
	return self;
}

-(NSError *)serializeToXMLQuery:(xmlNodePtr *)query
{
	
	xmlNodePtr findRequest = NULL;
	findRequest = xmlNewNode(NULL, BAD_CAST "FindNearby");
    xmlNewProp(findRequest, BAD_CAST "xmlns", BAD_CAST "http://s.mappoint.net/mappoint-30/");
	
	
	xmlNodePtr request = xmlNewNode(NULL, BAD_CAST "specification");
	xmlAddChild(findRequest, request);
	[self addStandardAttributesToNode:request];
	
	xmlNodePtr datasourceName = xmlNewNode(NULL, BAD_CAST "DataSourceName");
	xmlNodeSetContent(datasourceName, BAD_CAST [self.datasourceName cStringUsingEncoding:NSASCIIStringEncoding]);
	xmlAddChild(request, datasourceName);
	
	xmlNodePtr location = xmlNewNode(NULL, BAD_CAST "LatLong");
	[VELocationUtilities addMappointLocation:self.location toNode:location];
	xmlAddChild(request, location);
	
	
	xmlNodePtr distance = xmlNewNode(NULL, BAD_CAST "Distance");
	xmlNodeSetContent(distance, BAD_CAST [[NSString stringWithFormat:@"%f", self.distance] cStringUsingEncoding:NSASCIIStringEncoding]);
	xmlAddChild(request, distance);
	
	xmlNodePtr filter = xmlNewNode(NULL, BAD_CAST "Filter");
	xmlNodePtr entityTypeName = xmlNewNode(NULL, BAD_CAST "EntityTypeName");
	xmlNodeSetContent(entityTypeName, BAD_CAST [self.filter cStringUsingEncoding:NSASCIIStringEncoding]);
	xmlAddChild(filter, entityTypeName);
	xmlAddChild(request, filter);
	
	
	xmlNodePtr options = xmlNewNode(NULL, BAD_CAST "Options");
	xmlNodePtr range = xmlNewNode(NULL, BAD_CAST "Range");
	xmlAddChild(options, range);
	xmlNodePtr count = xmlNewNode(NULL, BAD_CAST "Count");
	xmlAddChild(range, count);
	xmlNodeSetContent(count, BAD_CAST [[NSString stringWithFormat:@"%i", self.range.length] cStringUsingEncoding:NSASCIIStringEncoding]);
	xmlNodePtr searchContext = xmlNewNode(NULL, BAD_CAST "SearchContext");
	xmlAddChild(options, searchContext);
	xmlNodeSetContent(searchContext, BAD_CAST "0");
	xmlNodePtr resultMask = xmlNewNode(NULL, BAD_CAST "ResultMask");
	xmlAddChild(options, resultMask);
	xmlAddChild(request, options);
	
	*query=findRequest;
	return nil;
}

@end
