//
//  SimpleMapView.m
//

#import "SimpleMapView.h"
#define LOCALIZED_STRINGS_TABLE @"SimpleMapViewLocalized"

@interface SimpleMapAnnotation : NSObject<MKAnnotation>

@property (nonatomic) CLLocationCoordinate2D coordinate;

@property (copy, nonatomic) NSString * title;
@property (copy, nonatomic) NSString * subtitle;

@end

@implementation SimpleMapAnnotation

@end

static CLLocationCoordinate2D validCoordinate(CLLocationCoordinate2D untrustedCoordinate) {
	CLLocationCoordinate2D coordinate = untrustedCoordinate;

	if (isnan(coordinate.latitude))//|| coordinate.latitude < -90 || coordinate.latitude > 90)
		coordinate.latitude = 0;
	if (isnan(coordinate.longitude))// || coordinate.longitude < -90 || coordinate.longitude > 90
		coordinate.longitude = 0;

	return coordinate;
}
static double validLatitudinalMeters(double v) {
	return MIN(v, 19500000);
}

@interface SimpleMapView ()

@property (nonatomic, strong) CLGeocoder * geocoder;

@end

@implementation SimpleMapView {
	SimpleMapAnnotation * firstAnnotation;
}

- (void)awakeFromNib {
	[super awakeFromNib];
}

- (void)setFirstAnnotationJSONString:(NSString *)firstAnnotationJSONString {
	
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
		
		NSDictionary * firstAnnotationInfo = [NSJSONSerialization JSONObjectWithData:[firstAnnotationJSONString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
		if (!firstAnnotation) firstAnnotation = [SimpleMapAnnotation new];
		firstAnnotation.title = firstAnnotationInfo[@"title"];
		firstAnnotation.subtitle = firstAnnotationInfo[@"subtitle"];
		
		
		if ([firstAnnotationInfo[@"positionMode"] isEqualToString:@"search"]) {
			NSString * query = firstAnnotationInfo[@"query"];
			[self searchWithQuery:query];
			
		}
		else {
			CLLocationCoordinate2D coordinate = { [firstAnnotationInfo[@"latitude"] doubleValue], [firstAnnotationInfo[@"longitude"] doubleValue] };
			coordinate = validCoordinate(coordinate);
			firstAnnotation.coordinate = coordinate;
			CLLocationCoordinate2D center = coordinate;//{ self.latitude.doubleValue, self.longitude.doubleValue };

			MKCoordinateRegion adjustedRegion = MKCoordinateRegionMakeWithDistance(center, validLatitudinalMeters(self.latitudinalMeters.doubleValue), 0);

			[self setRegion:adjustedRegion animated:NO];
			[self addAndSelectAnnotation:firstAnnotation animated:NO];

		}
	});
		

}

- (void)addAndSelectAnnotation:(id<MKAnnotation>)annotation animated:(BOOL)animated {
	[self addAnnotation:annotation];
	[self selectAnnotation:annotation animated:animated];
}

- (void)searchWithQuery:(NSString *)query {
	
	if (!query.length) return;
	
	if (self.geocoder) {
		[self.geocoder cancelGeocode];
	}
	//else {
		self.geocoder = [[CLGeocoder alloc] init];
	//}
	//self.hidden = YES;
	[self.geocoder geocodeAddressString:query
				 completionHandler:^(NSArray* placemarks, NSError* error) {
					 if (error) {
						 NSLog(@"Error: %@", error);
						 return;
					 }
					 self.hidden = NO;
					 for (CLPlacemark* aPlacemark in placemarks)
					 {
						 firstAnnotation.coordinate = aPlacemark.location.coordinate;
						 [self addAndSelectAnnotation:firstAnnotation animated:NO];
						 CLLocationCoordinate2D center = { firstAnnotation.coordinate.latitude, firstAnnotation.coordinate.longitude };
						 self.region = MKCoordinateRegionMakeWithDistance(validCoordinate(center), self.latitudinalMeters.doubleValue, 0);
						 break;
					 }
				 }];

}

- (void)setSingleAnnotationQuery:(NSString *)singleAnnotationQuery {
	if (!singleAnnotationQuery.length) return;
	[self searchWithQuery:singleAnnotationQuery];
}

- (void)setSingleAnnotationLatitude:(NSNumber *)value {
	CLLocationCoordinate2D coordinate = firstAnnotation.coordinate;
	coordinate.latitude = value.doubleValue;
	[self setSingleAnnotationCoordinate:coordinate];
}

- (void)setSingleAnnotationLongitude:(NSNumber *)value {
	CLLocationCoordinate2D coordinate = firstAnnotation.coordinate;
	coordinate.longitude = value.doubleValue;
	[self setSingleAnnotationCoordinate:coordinate];
}

- (void)setSingleAnnotationCoordinate:(CLLocationCoordinate2D)coordinate {
	firstAnnotation.coordinate = coordinate;
	if (self.annotations.count) [self removeAnnotation:firstAnnotation];
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
		if (self.annotations.count) return;
		[self addAnnotation:firstAnnotation];
	});
}

- (void)setLatitudinalMetersByUpdate:(NSNumber *)value {
	MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(self.region.center, validLatitudinalMeters(value.doubleValue), 0);
	[self setRegion:region animated:YES];
}

- (void)setMapType:(MKMapType)mapType {
	[super setMapType:mapType];
}
@end
