#include "AppDelegate.h"
#include "GeneratedPluginRegistrant.h"
#import "GoogleMaps/GoogleMaps.h"
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [GMSServices provideAPIKey:@"AIzaSyAb9JNtW0BEZ_qLeDg87ZhvxSmZply-7hU"];
    
    FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
    
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"make.photo.screen.hibok"
                                     binaryMessenger:controller];
    
    [channel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        if ([@"makePhotoScreen" isEqualToString:call.method]) {
            UIImage* img  = [self makePhotoScreen: controller.view];

            NSData *imageData = UIImageJPEGRepresentation(img, 0.8);
            FlutterStandardTypedData* value  = [FlutterStandardTypedData typedDataWithBytes:imageData];
            
            result(value);
        }else if([@"openMapForOth" isEqualToString:call.method]){
                     NSDictionary* params = call.arguments;
                     NSString* mapType = params[@"mapType"];
                     NSArray* latLng = params[@"latLng"];
                     NSString* address = params[@"address"];

                     [self openMapForOth:mapType latLng:latLng adress:address];
                 }else if([@"getListForMap" isEqualToString:call.method]){
            NSArray* supportMaps  = [self getListForMap];
            result(supportMaps);
        }
        else
        {
            result(FlutterMethodNotImplemented);
        }
    }];
    
    
     // 创建eventChannel 代理方法里处理stream流 delegate设置为self
    FlutterEventChannel *eventChannel = [FlutterEventChannel eventChannelWithName:@"com.file.hibok" binaryMessenger:controller];
    [eventChannel setStreamHandler:self];
     
    [GeneratedPluginRegistrant registerWithRegistry:self];
    
    
    if(![[NSUserDefaults standardUserDefaults]objectForKey:@"Notification"]){
           [[UIApplication sharedApplication] cancelAllLocalNotifications];
           [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"Notification"];
       }
    
    // Override point for customization after application launch.
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}



#pragma mark - FlutterStreamHandler
- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)eventSink{
    self.eventSink = eventSink;
    return nil;
}
 
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments {
    return nil;
}

- (UIImage*)makePhotoScreen:(UIView*)view {
    
    CGSize size = view.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //   CGImageRef imageRef =image.CGImage;
    
    //    CGRect rect =  CGRectMake(CGImageGetWidth(imageRef)/4, CGImageGetHeight(imageRef)/2-CGImageGetWidth(imageRef)/2, CGImageGetWidth(imageRef)/2, CGImageGetWidth(imageRef)/2);//这里可以设置想要截图的区域
    //
    //    CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
    //
    //    UIImage *sendImage =[[UIImage alloc] initWithCGImage:imageRefRect];
    //
    //
    
    return image;
}

- (NSArray*)getListForMap{
    
    NSMutableArray* maps = [[NSMutableArray alloc] init];
    
    //苹果地图
    [maps addObject:@"apple"];


     //谷歌地图

        if([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"comgooglemaps://"]]) {
            [maps addObject:@"google"];

        }

     //高德地图

        if([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
            [maps addObject:@"minimap"];
        }
    
    //百度地图
    
    if([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:@"baidumap://"]]) {
        [maps addObject:@"baidu"];
    }
    

    

    
    
    return maps;
    
}

-(void) openMapForOth:(NSString *)mapType latLng:(NSArray*)latLng adress:(NSString*)adress {
    
    if([mapType isEqualToString:@"baidu"]){
        NSString*urlString = [[NSString stringWithFormat:@"baidumap://map/geocoder?location=%@f,%@f&coord_type=gcj02&src=com.cyhd.henhoandroid",latLng.firstObject, latLng.lastObject] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString:urlString]];
        
    }else if([mapType isEqualToString:@"minimap"]){
        
        NSString*urlString = [[NSString stringWithFormat:@"iosamap://navi?sourceApplication= &lat=%@f&lon=%@f&dev=1",latLng.firstObject, latLng.lastObject] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString:urlString]];
        
    }else if([mapType isEqualToString:@"apple"]){

             NSString*urlString = [[NSString stringWithFormat:@"http://maps.apple.com/?daddr=%@f,%@f",latLng.firstObject, latLng.lastObject] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
             [[UIApplication sharedApplication] openURL: [NSURL URLWithString:urlString]];

         }else if([mapType isEqualToString:@"google"]){
        
        NSString*urlString = [[NSString stringWithFormat:@"comgooglemaps://?daddr=%@f,%@f",latLng.firstObject, latLng.lastObject] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString:urlString]];
    }
    
}


- (void)applicationDidEnterBackground:(UIApplication *)application {


    self.task = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        [[UIApplication sharedApplication] endBackgroundTask:self.task];
        self.task = UIBackgroundTaskInvalid;

    }];


//    __block int count = 0;
//    [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
//
//        count ++;
//        NSLog(@"%d",count);
//
//    }];

}


//申请后台运行权限
- (void)backGroundSpeech {
    UIApplication *app = [UIApplication sharedApplication];
    __block UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid)
            {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    });
}






#pragma mark ------------------  结束后台任务 ------------------
- (void)endBackgroundUpdateask{
    [[UIApplication sharedApplication] endBackgroundTask:self.task];
           self.task = UIBackgroundTaskInvalid;
}




- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    
    NSLog(@"myurl %@",url.absoluteString);
    
//     if (url != nil) {
////         不跟分享插件冲突
//     if ([url.absoluteString containsString:@"SharePhotos"]) {
//         NSLog(@"myurl 存在");
//
//     }
//     }
         
    if (url != nil && [url.absoluteString containsString:@"file:///private"]) {
         NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths lastObject];
            if (url != nil) {
                NSString *path = [url absoluteString];
                path = [path stringByRemovingPercentEncoding];
                NSMutableString *string = [[NSMutableString alloc] initWithString:path];
                if ([path hasPrefix:@"file:///private"]) {
                    [string replaceOccurrencesOfString:@"file:///private" withString:@"" options:NSCaseInsensitiveSearch  range:NSMakeRange(0, path.length)];
                }
                NSArray *tempArray = [string componentsSeparatedByString:@"/"];
                NSString *fileName = tempArray.lastObject;
                NSString *sourceName = options[@"UIApplicationOpenURLOptionsSourceApplicationKey"];
                
                NSFileManager *fileManager = [NSFileManager defaultManager];
                NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
                if ([fileManager fileExistsAtPath:filePath]) {
                    NSLog(@"文件已存在");
                    self.eventSink(filePath);
        //            [SVProgressHUD showErrorWithStatus:@"文件已存在"];
                    return YES;
                }
        //        [MRTools creatFilePathInManager:sourceName];
                
                BOOL isSuccess = [fileManager copyItemAtPath:string toPath:filePath error:nil];
                if (isSuccess == YES) {
                    NSLog(@"拷贝成功");
                    self.eventSink(filePath);
        //            [SVProgressHUD showSuccessWithStatus:@"文件拷贝成功"];
                } else {
                    NSLog(@"拷贝失败");
        //            [SVProgressHUD showErrorWithStatus:@"文件拷贝失败"];
                }
            }
    }else{
        [super application:self openURL:url options:nil];
              return  YES;
    }
    
   
   
    NSLog(@"application:openURL:options:");
    return  YES;
}


@end
