//
// SMMapView.m
// Project
//
// Created by haibara on 2/21/17.
//
//

#import "SMMapView.h"
#import "Lang.h"
#import "SDK.h"
#import <BlocksKit/BlocksKit.h>

@interface MKMapView ()
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
@end

@interface SMMapView ()
@property (nonatomic, assign) BOOL hidesCompass;
@end

@implementation SMMapView

@dynamic showsCompass;

- (id)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
	if (self) {
		self.calloutView = [[SMModernCalloutView alloc] init];
	}
	return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
	self = [super initWithCoder:decoder];
	if (self) {
		self.calloutView = [[SMModernCalloutView alloc] init];
	}
	return self;
}

- (void)layoutSubviews {
	[super layoutSubviews];

	if ([SystemUtils isOperatingSystemAtLeastVersion:NSOperatingSystemVersionMake(9, 0, 0)]) {
	} else if (self.hidesCompass) {
		UIView *view = [self.subviews bk_match:^BOOL (UIView *obj) {
			return [obj isKindOfClass:NSClassFromString(@"MKCompassView")];
		}];
		view.hidden = YES;
	}
}

// override UIGestureRecognizer's delegate method so we can prevent MKMapView's recognizer from firing
// when we interact with UIControl subclasses inside our callout view.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
	if ([touch.view isKindOfClass:[UIControl class]]) {
		return NO;
	} else {
		return [super gestureRecognizer:gestureRecognizer shouldReceiveTouch:touch];
	}
}

// Allow touches to be sent to our calloutview.
// See this for some discussion of why we need to override this: https://github.com/nfarina/calloutview/pull/9
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
	UIView *calloutMaybe = [self.calloutView hitTest:[self.calloutView convertPoint:point fromView:self] withEvent:event];
	if (calloutMaybe) {
		return calloutMaybe;
	}
	return [super hitTest:point withEvent:event];
}

#pragma mark - Property

- (BOOL)showsCompass {
	if ([SystemUtils isOperatingSystemAtLeastVersion:NSOperatingSystemVersionMake(9, 0, 0)]) {
		return [super showsCompass];
	} else {
		return !self.hidesCompass;
	}
}

- (void)setShowsCompass:(BOOL)showsCompass {
	if ([SystemUtils isOperatingSystemAtLeastVersion:NSOperatingSystemVersionMake(9, 0, 0)]) {
		[super setShowsCompass:showsCompass];
	} else {
		self.hidesCompass = !showsCompass;
	}
}

#pragma mark

- (void)dealloc {
	if (!self.calloutView.popupCancelled) {
		[self.calloutView dismissCalloutAnimated:NO];
	}
}

@end
