//
//  RNSFLocation.m
//  RNSFLocation
//
//  Created by SmartFun on 2018/7/26.
//  Copyright © 2018年 SmartFun. All rights reserved.
//

#import "RNSFLocation.h"
#import <React/RCTConvert.h>
#import <React/RCTUtils.h>
#import "RNLocation.h"
#import <React/RCTEventDispatcher.h>
#import "AMapFoundationKit.h"
#import "AMapLocationKit.h"

@interface RNSFLocation() <AMapLocationManagerDelegate>
@property (nonatomic, strong) RCTResponseSenderBlock callback;
@property (nonatomic, strong) AMapLocationManager         *locationManager;
@end


@implementation RNSFLocation

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE();

RCT_EXPORT_METHOD(chooseCity:(RCTResponseSenderBlock)callback) {
    self.callback = callback;
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *root = RCTPresentedViewController();
        RNLocation *vc = [[RNLocation alloc] init];
        vc.callback = self.callback;
        [root presentViewController:vc animated:YES completion:nil];
    });
}

RCT_EXPORT_METHOD(initLocation:(NSString *)key){
    [self initLocations:key];
}

RCT_EXPORT_METHOD(getLocation) {
    [self getLocations];
}

- (void)initLocations:(NSString *)key{
    [AMapServices sharedServices].apiKey = key;
}

-(void)getLocations{
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
    self.locationManager.locationTimeout = 5;
    self.locationManager.reGeocodeTimeout = 5;
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        NSLog(@"location:%@", location);
        if (regeocode)
        {
            NSMutableDictionary *resultDic = [NSMutableDictionary dictionary];
            NSLog(@"-----------reGeocode:%@", regeocode);
            resultDic[@"latitude"] = @(location.coordinate.latitude);
            resultDic[@"longitude"] = @(location.coordinate.longitude);
            resultDic[@"cityCode"] = regeocode.citycode;
            resultDic[@"city"] = regeocode.city;
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.bridge.eventDispatcher sendAppEventWithName:@"locationListener" body:resultDic];
            });
            
        }
    }];
}

- (void)stopLocation{
    [self.locationManager stopUpdatingLocation];
}

- (void)destroyLocation {
    [self.locationManager stopUpdatingLocation];
    self.locationManager = nil;
}

- (AMapLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        _locationManager.delegate = self;
    }
    return _locationManager;
}

@end
