//
//  AppDelegate.m
//  唔即云相册
//
//  Created by 余衡武 on 2021/12/8.
//

#import "AppDelegate.h"
#import <CoreMotion/CoreMotion.h>
#import "ShearDeviceUDPManager.h"
#import "AudioSessionObject.h"
#import "DDYLanguageTool.h"
#import "AFNetworkReachabilityManager.h"
#import "PLeakSniffer.h"

@interface AppDelegate (){
    CMMotionManager *cmManager;
}

@end

@implementation AppDelegate

+ (AppDelegate*)sharedAppDelegate
{
    static AppDelegate *appDelegate = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (appDelegate == nil) {
            appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
        }
    });
    
    return appDelegate;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    [self setLanguagesFun];
    
    //设置默认值
//    self.couldPhone_W_PHONE = 720.0;
//    self.couldPhone_H_PHONE = 1280.0;
    
    self.couldPhone_W_PHONE = 1080.0;
    self.couldPhone_H_PHONE = 1920.0;
    
    [[UIButton appearance] setExclusiveTouch:YES];
    
    cmManager = [[CMMotionManager alloc] init];
    if (cmManager.isAccelerometerAvailable){
        HLog(@"\n-------摇一摇可用-----");
    }else{
        HLog(@"\n-------摇一摇不可用-----");
    }
    cmManager.accelerometerUpdateInterval = 0.1;
    [cmManager startAccelerometerUpdates];
    [cmManager startDeviceMotionUpdatesToQueue:[NSOperationQueue new] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
//        CMRotationRate rotationRate = motion.rotationRate;
//        CGFloat rotationRatex = rotationRate.x;
//        CGFloat rotationRatey = rotationRate.y;
//        CGFloat rotationRatez = rotationRate.z;
        
        CMAcceleration accrleration = motion.gravity;
        CGFloat rotationGravityz = accrleration.z;
        
        //HLog(@"rotationRatey: %f",rotationRatey)
        //HLog(@"rotationGravityz: %f",rotationGravityz)
        
        //if (rotationRatey > 7){
        if (rotationGravityz > 0.85){
            
            BOOL haveOpenMask = [HWDataManager getBoolWithKey:Consn_Fanzhuan_Exit_app_Open];
            if (haveOpenMask){
                exit(0);/*强制退出app*/
            }
        }
    }];
    
//    [[ShearDeviceUDPManager shareInstance] startShearchDevice];
//    [[ShearDeviceUDPManager shareInstance] shearchDeviceLoop];
    
    
    //启动后台保活
    [AudioSessionObject shareManager];
    [self MonitorNetworkChangesFun];
    
    [[PLeakSniffer sharedInstance] installLeakSniffer];
    
    return YES;
}

/// 在这里写支持的旋转方向，为了防止横屏方向，应用启动时候界面变为横屏模式
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    return UIInterfaceOrientationMaskPortrait;
}


#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        NSString *orderNumber = [HWDataManager getStringWithKey:Const_AirpayOrWXorderNum];
        if (orderNumber && ![orderNumber isEqualToString:@""])
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:NotNameAirpayOrWXorderNum object:orderNumber];
        }
    });
}

#pragma mark 监听网络变化
-(void)MonitorNetworkChangesFun
{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        HLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

        [[NSNotificationCenter defaultCenter] postNotificationName:NetWorkChangeNotification object:nil];
    }];

    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
}

#pragma mark 多国语言相关
-(void)setLanguagesFun{
    NSArray *arLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSLog(@"arLanguages:%@",arLanguages);
    ///获取设备当前地区的代码和APP语言环境
    NSString *languageCode = [NSLocale preferredLanguages][0];
    // 获取国际通用国家地区代码（应该和手机本身有关）
    NSString *countryCode = [NSString stringWithFormat:@"-%@", [[NSLocale currentLocale] objectForKey:NSLocaleCountryCode]];
//    if (languageCode) {
//        languageCode = [languageCode stringByReplacingOccurrencesOfString:countryCode withString:@""];
//    }
    NSLog(@"countryCode：%@ languageCode : %@",countryCode, languageCode);
    ///当前APP使用的语言
    NSString *preferredLanguage = [[[NSBundle mainBundle] preferredLocalizations] firstObject];
    //获取设备当前地区的代码和APP语言环境
    NSString *localeIdentifier = [[NSLocale currentLocale] objectForKey:NSLocaleIdentifier];
    NSLog(@"preferredLanguage：%@ localeIdentifier : %@",preferredLanguage, localeIdentifier);
    
    //目前支持 中文（简体 繁体） 英文 日语（还没做）
    if([languageCode  rangeOfString:preferredLanguage].location != NSNotFound){
//        if([preferredLanguage rangeOfString:@"ja"].location != NSNotFound){
//            //日文现在也显示英文
//            [self setDefaultEnglishFun];
//        }
//        else
        {
            [DDYLanguageTool ddy_SetLanguage:@"" complete:^(NSError *error) {
                   // 刷新rootVC等
            }];
        }
    }
    else{
        [self setDefaultEnglishFun];
    }
}

#pragma mark 设置当前显示语言为中文
- (void)setDefaultEnglishFun{
    //默认设为英文
    [DDYLanguageTool ddy_SetLanguage:@"en" complete:^(NSError *error) {
           // 刷新rootVC等
    }];
}
@end
