//#import <AppDelegate.h>
#import "RNAmapNavi.h"
#import "AMapNaviDriveVC.h"
#import <AMapNaviKit/AMapNaviKit.h>

@interface RNAmapNavi ()<AMapNaviDriveManagerDelegate>

@property (nonatomic, strong) RCTPromiseResolveBlock resolve;
@property (nonatomic, strong) RCTPromiseRejectBlock reject;


@end

@implementation RNAmapNavi


- (instancetype)init
{
    if (self = [super init]) {
        [[AMapNaviManagerConfig sharedConfig] updatePrivacyShow:AMapPrivacyShowStatusDidShow privacyInfo:AMapPrivacyInfoStatusDidContain];
        [[AMapNaviManagerConfig sharedConfig] updatePrivacyAgree:AMapPrivacyAgreeStatusDidAgree];
    }
    return self;
}

RCT_EXPORT_MODULE()

/**
 驾车导航 不使用导航组件 自定义导航界面
 */
RCT_EXPORT_METHOD(startDrivingNavigationView:(NSDictionary*)startPoi endPoi:(NSDictionary*)endPoi wayPOIInfos:(NSArray*)wayPOIInfos drivingStrategy:(NSInteger)drivingStrategy drivingDistance:(NSInteger)drivingDistance){
    dispatch_async(dispatch_get_main_queue(), ^{
        AMapNaviDriveVC *VC = [[AMapNaviDriveVC alloc] init];
        VC.startPoi=startPoi;
        VC.endPoi=endPoi;
        VC.wayPOIInfos=wayPOIInfos;
        VC.drivingStrategy=drivingStrategy;
        VC.drivingDistance=drivingDistance;
        UIViewController *container= [UIApplication sharedApplication].keyWindow.rootViewController;
        [container presentViewController:VC animated:true completion:nil];
    });
}

- (NSArray*)array2AMapNaviPointArray:(NSArray*)array
{
    NSMutableArray *wayPoints = [[NSMutableArray alloc] init];
    NSUInteger count = array.count;
    for( int i=0; i<count; i++){
        NSDictionary * dic=[array objectAtIndex:i];
        AMapNaviPoint *point=  [AMapNaviPoint locationWithLatitude:[[dic objectForKey:@"latitude"] doubleValue] longitude:[[dic objectForKey:@"longitude"] doubleValue]];
        [wayPoints addObject:point];
    }
    return wayPoints;
}

/**
 *算路
 */
RCT_EXPORT_METHOD(calculateDriveRoute:(NSDictionary*)startPoi endPoi:(NSDictionary*)endPoi wayPOIInfos:(NSArray*)wayPOIInfos drivingStrategy:(NSInteger)drivingStrategy findEventsWithResolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
    [[AMapNaviDriveManager sharedInstance] setDelegate:self];
    self.resolve=resolve;
    self.reject=reject;
    NSArray *wayPoints=[self array2AMapNaviPointArray:wayPOIInfos];
    [[AMapNaviDriveManager sharedInstance] calculateDriveRouteWithStartPoints:@[[AMapNaviPoint locationWithLatitude:[[startPoi objectForKey:@"latitude"] doubleValue] longitude:[[startPoi objectForKey:@"longitude"] doubleValue]]] endPoints:@[[AMapNaviPoint locationWithLatitude:[[endPoi objectForKey:@"latitude"] doubleValue] longitude:[[endPoi objectForKey:@"longitude"] doubleValue]]] wayPoints:wayPoints drivingStrategy:drivingStrategy];
}


- (void)driveManager:(AMapNaviDriveManager *)driveManager onCalculateRouteSuccessWithType:(AMapNaviRoutePlanType)type;
{
    NSLog(@"onCalculateRouteSuccess");
    if(_resolve==nil)
        return;
    NSMutableArray* routes= [[NSMutableArray alloc] init];
    if ([[AMapNaviDriveManager sharedInstance].naviRoutes count] <= 0) {
        _resolve(routes);
        return;
    }
    for (NSNumber *aRouteID in [[AMapNaviDriveManager sharedInstance].naviRoutes allKeys])
    {
        NSMutableDictionary * route=[[NSMutableDictionary alloc] init];
        AMapNaviRoute *aRoute = [[[AMapNaviDriveManager sharedInstance] naviRoutes] objectForKey:aRouteID];
        int count = (int)[[aRoute routeCoordinates] count];
        NSMutableArray* coordinates=[[NSMutableArray alloc] init];
        for (int i = 0; i < count; i++)
        {
            AMapNaviPoint *coordinate = [[aRoute routeCoordinates] objectAtIndex:i];
            NSDictionary *dict = @{@"latitude":[NSNumber numberWithFloat:coordinate.latitude], @"longitude":[NSNumber numberWithFloat:coordinate.longitude]};
            [coordinates addObject:dict];
        }
        [route setValue:coordinates forKey:@"coordList"];
        [route setObject:[NSNumber numberWithLong:(long)aRoute.routeLength] forKey:@"allLength"];
        [route setObject:[NSNumber numberWithLong:(long)aRoute.routeTime] forKey:@"allTime"];
        [route setObject:aRoute.routeLabels forKey:@"labels"];
        //        [route setObject:aRoute.routeLabels forKey:@"mainRoadInfo"];
        [route setObject:[NSNumber numberWithLong:aRoute.routeUID] forKey:@"pathId"];
        [route setObject:[NSNumber numberWithLong:aRoute.routeTollCost] forKey:@"tollCost"];
        [routes addObject:route];
    }
    _resolve(routes);
    _resolve=nil;
}

// 算路失败后的回调函数,路径规划页面的算路、导航页面的重算等失败后均会调用此方法
- (void)compositeManager:(AMapNaviCompositeManager *)compositeManager onCalculateRouteFailure:(NSError *)error {
    NSLog(@"onCalculateRouteFailure error:{%ld - %@}", (long)error.code, error.localizedDescription);
    if(_reject==nil)
        return;
    _reject(error.localizedDescription,nil ,nil);
    _reject=nil;
}


@end
