//
//  AmapLocation.m
//  nativeModules
//
//  Created by Lucifer on 2017/8/9.
//  Copyright © 2017年 drwine. All rights reserved.
//

#import "AmapLocation.h"
#import <AMapFoundationKit/AMapFoundationKit.h>

#import <AMapLocationKit/AMapLocationKit.h>

#define DefaultLocationTimeout  15
#define DefaultReGeocodeTimeout 3

static AmapLocation *_amapinstance = nil;

@interface AmapLocation () <AMapLocationManagerDelegate>

@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, copy) AMapLocatingCompletionBlock completionBlock;
@property (nonatomic, copy) RCTResponseSenderBlock geoCallback;

@end


@implementation AmapLocation

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE(DRAmapLocation)

RCT_EXPORT_METHOD(getCurrentLocation:(RCTResponseSenderBlock)callback){
    [[AmapLocation sharedInstance] locationAction];
    [AmapLocation sharedInstance].geoCallback = [callback copy];
}

#pragma mark class me

+ (instancetype)sharedInstance {
    
    if(_amapinstance == nil) {
        _amapinstance = [[AmapLocation alloc] init];
    }
    return _amapinstance;
}

+(void)signAmapLocationkey:(NSString *)appkey{
    AmapLocation *amap = [AmapLocation sharedInstance];
    [amap configLocationManager];
    [amap initCompleteBlock];
    [AMapServices sharedServices].apiKey = appkey;
}


- (void)configLocationManager
{
    [AmapLocation sharedInstance].locationManager = [[AMapLocationManager alloc] init];
    
    [[AmapLocation sharedInstance].locationManager setDelegate:[AmapLocation sharedInstance]];
    
    //设置期望定位精度
    [[AmapLocation sharedInstance].locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
    
    //设置不允许系统暂停定位
    [[AmapLocation sharedInstance].locationManager setPausesLocationUpdatesAutomatically:NO];
    
    //设置允许在后台定位
//    [[AmapLocation sharedInstance].locationManager setAllowsBackgroundLocationUpdates:YES];
    
    //设置定位超时时间
    [[AmapLocation sharedInstance].locationManager setLocationTimeout:DefaultLocationTimeout];
    
    //设置逆地理超时时间
    [[AmapLocation sharedInstance].locationManager setReGeocodeTimeout:DefaultReGeocodeTimeout];
    
    //设置开启虚拟定位风险监测，可以根据需要开启
    [[AmapLocation sharedInstance].locationManager setDetectRiskOfFakeLocation:NO];
}

- (void)initCompleteBlock
{
    [AmapLocation sharedInstance].completionBlock = ^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error)
    {
        if (error != nil && error.code == AMapLocationErrorLocateFailed)
        {
            //定位错误：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"定位错误:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else if (error != nil
                 && (error.code == AMapLocationErrorReGeocodeFailed
                     || error.code == AMapLocationErrorTimeOut
                     || error.code == AMapLocationErrorCannotFindHost
                     || error.code == AMapLocationErrorBadURL
                     || error.code == AMapLocationErrorNotConnectedToInternet
                     || error.code == AMapLocationErrorCannotConnectToHost))
        {
            //逆地理错误：在带逆地理的单次定位中，逆地理过程可能发生错误，此时location有返回值，regeocode无返回值，进行annotation的添加
            NSLog(@"逆地理错误:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        else if (error != nil && error.code == AMapLocationErrorRiskOfFakeLocation)
        {
            //存在虚拟定位的风险：此时location和regeocode没有返回值，不进行annotation的添加
            NSLog(@"存在虚拟定位的风险:{%ld - %@};", (long)error.code, error.localizedDescription);
            return;
        }
        else
        {
            //没有错误：location有返回值，regeocode是否有返回值取决于是否进行逆地理操作，进行annotation的添加
            NSLog(@"location: --- success----");
            NSLog(@"location:%@", location);
            NSMutableDictionary *datadic = [[NSMutableDictionary alloc]init];
            [datadic setValue:[NSNumber numberWithDouble:location.coordinate.latitude] forKey:@"latitude"];
            [datadic setValue:[NSNumber numberWithDouble:location.coordinate.longitude] forKey:@"longitude"];
            [AmapLocation sharedInstance].geoCallback(@[datadic]);
        }
    };
}

- (void)locationAction{
    [[AmapLocation sharedInstance].locationManager requestLocationWithReGeocode:NO completionBlock:[AmapLocation sharedInstance].completionBlock];
}

@end
