//
//  YYRootViewController.m
//  YYObjCDemo
//
//  Created by Daniel Bey on 2017年06月16日.
//  Copyright © 2017 百度鹰眼. All rights reserved.
//

#import "YYMainViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import "YYNotificationHandler.h"
#define kBaiduMapAgreedPrivacyFlag @"kBaiduMapAgreedPrivacyFlag"

@interface YYMainViewController () <BMKGeneralDelegate, BTKAuthDelegate>
@property (nonatomic, strong) YYNotificationHandler *notificationHandler;
@property (nonatomic, strong) UIButton *customButton;
@property (nonatomic, strong) BMKMapManager *mapManager; //主引擎类
@property (nonatomic, assign) BOOL hasInitSDK;
@property (nonatomic, copy) NSArray *functionList;
@end

@implementation YYMainViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    UIBarButtonItem *customButton = [[UIBarButtonItem alloc] initWithCustomView:self.customButton];
    self.navigationItem.rightBarButtonItem = customButton;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
}

#pragma mark - Responding events
- (void)clickCustomButton {
    if (!self.hasInitSDK) {
        [self initBaiduMapSDK];
        [self initYingYanSDK];
        self.hasInitSDK = YES;
    } else if (![[NSUserDefaults standardUserDefaults] boolForKey:kBaiduMapAgreedPrivacyFlag]) {
        [self showAgreePrivacyAlert];
    } else {
        [self showHasInitedSDKAlert];
    }
}

#pragma mark - 地图SDK初始化
- (void)initBaiduMapSDK {
    
    // 初始化地图SDK
    BMKMapManager *mapManager = [[BMKMapManager alloc] init];
    [mapManager start:AK generalDelegate:self];
    
    // 鹰眼SDK鉴权 since 3.2.0
    BTKAuthManager *yyManager = [BTKAuthManager sharedInstance];
    [yyManager start:AK generalDelegate:self];
    
    // 设置鹰眼SDK的基础信息
    // 每次调用startService开启轨迹服务之前，可以重新设置这些信息。
    BTKServiceOption *basicInfoOption = [[BTKServiceOption alloc] initWithAK:AK mcode:MCODE serviceID:serviceID keepAlive:FALSE];
    [[BTKAction sharedInstance] initInfo:basicInfoOption];
    
    if (![[NSUserDefaults standardUserDefaults] boolForKey:kBaiduMapAgreedPrivacyFlag]) {
        [self showAgreePrivacyAlert];
    } else {
        // 地图SDK隐私权限授权
        [BMKMapManager setAgreePrivacy:YES];
        // 鹰眼SDK隐私权限授权
        [BTKPrivacyAuthorization setAgreePrivacy:YES];
    }
}

- (void)initYingYanSDK {
    // 申请通知权限
    if (CURRENT_IOS_VERSION >= 10.0) {
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                NSLog(@"已经获取通知权限");
            }
        }];
    }
    
    // 注册通知
    [UNUserNotificationCenter currentNotificationCenter].delegate = self.notificationHandler;
}


/**
 联网结果回调

 @param iError 联网结果错误码信息，0代表联网成功
 */
- (void)onGetNetworkState:(int)iError {
    if (0 == iError) {
        NSLog(@"联网成功");
    } else {
        NSLog(@"联网失败：%d", iError);
    }
}

/**
 鉴权结果回调

 @param iError 鉴权结果错误码信息，0代表鉴权成功
 */
- (void)onGetPermissionState:(int)iError {
    if (0 == iError) {
        NSLog(@"授权成功");
    } else {
        NSLog(@"授权失败：%d", iError);
    }
}

- (void)authOnGetNetworkState:(int)iError {
    if (0 == iError) {
        NSLog(@"鹰眼SDK联网成功");
    } else {
        NSLog(@"authOnGetNetworkState %d", iError);
    }
}

- (void)authOnGetPermissionState:(int)iError {
    if (0 == iError) {
        NSLog(@"鹰眼SDK授权成功");
    } else {
        NSLog(@"authOnGetPermissionState %d", iError);
    }
}

#pragma mark - setter & getter
-(YYNotificationHandler *)notificationHandler {
    if (_notificationHandler == nil) {
        _notificationHandler = [[YYNotificationHandler alloc] init];
    }
    return _notificationHandler;
}

#pragma mark - 隐私政策弹窗
- (void)showAgreePrivacyAlert {
    // ‼️重要：设置用户是否同意SDK隐私协议，必须SDK初始化前按用户意愿设置
    // 隐私政策官网链接：https://lbsyun.baidu.com/index.php?title=openprivacy
    NSString *message = @"\n欢迎您使用百度地图开放平台产品和服务,为响应工信部针对进一步加强用户隐私安全保障措施的号召，以便更好地为广大用户提供更合规、更安全、更稳定的服务体验，平台全面更新了《百度地图开放平台产品和服务隐私政策》,请认真阅读并同意隐私服务政策";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"同意" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kBaiduMapAgreedPrivacyFlag];
        [[NSUserDefaults standardUserDefaults] synchronize];
        // 地图SDK隐私权限授权
        [BMKMapManager setAgreePrivacy:YES];
        // 鹰眼SDK隐私权限授权
        [BTKPrivacyAuthorization setAgreePrivacy:YES];
        [self performSelector:@selector(showHasInitedSDKAlert) withObject:nil afterDelay:0.5];
    }];

    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"不同意" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kBaiduMapAgreedPrivacyFlag];
        [[NSUserDefaults standardUserDefaults] synchronize];
        // 地图SDK隐私权限授权
        [BMKMapManager setAgreePrivacy:NO];
        // 鹰眼SDK隐私权限授权
        [BTKPrivacyAuthorization setAgreePrivacy:NO];
        [self performSelector:@selector(showHasDisagreePrivacyAgreementAlert) withObject:nil afterDelay:0.5];
    }];

    [alert addAction:conform];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showHasInitedSDKAlert {
    NSString *message = @"\n鹰眼和百度地图SDK初始化已完成，可以正常使用相关功能了～";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];

    [alert addAction:conform];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showHasDisagreePrivacyAgreementAlert {
    NSString *message = @"鹰眼SDK3.1.5版本增加隐私合规接口，设置用户是否同意鹰眼SDK隐私政策，默认不同意，设置为YES时才能创建Action，否则返回nil，将影响鹰眼SDK所有功能的使用。since 3.2.0起鹰眼SDK新增鉴权服务，使用鹰眼服务前请务必完成鉴权，否则影响功能使用。\n地图SDK6.5.1版本增加隐私合规接口，设置用户是否同意地图SDK隐私政策，默认不同意，设置为同意时才能创建BMKSearchBase及其子类对象，否则返回nil，将影响地图SDK所有检索组件功能的使用，地图展示及覆盖物能力不受影响。\n";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];

    [alert addAction:conform];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)showSDKInitTipAlert {
    NSString *message = @"\n需要先点击页面右上角按钮初始鹰眼和地图SDK～";

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *conform = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];

    [alert addAction:conform];
    [self presentViewController:alert animated:YES completion:nil];
}


#pragma mark - private function
- (void)setupUI {
    self.title = [NSString stringWithFormat:@"鹰眼SDK v%@ DEMO", BTKVersionNumber];
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] init];
    backBarButtonItem.title = @"返回";
    self.navigationItem.backBarButtonItem = backBarButtonItem;
    self.tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.tableView.separatorInset = UIEdgeInsetsZero;
}

#pragma mark - UITableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.functionList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"YYFunctionListCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.textLabel.font = [UIFont boldSystemFontOfSize:24];
    }
    cell.imageView.image = [UIImage imageNamed:self.functionList[indexPath.row][@"icon"]];
    CGSize itemSize = CGSizeMake(40, 40);
    UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
    CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
    [cell.imageView.image drawInRect:imageRect];
    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    cell.textLabel.text = self.functionList[indexPath.row][@"title"];
    cell.detailTextLabel.text = self.functionList[indexPath.row][@"detail"];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 60;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (!self.hasInitSDK) {
        [self showSDKInitTipAlert];
        return;
    }
    if (![[NSUserDefaults standardUserDefaults] boolForKey:kBaiduMapAgreedPrivacyFlag]) {
        [self showHasDisagreePrivacyAgreementAlert];
        return;
    }
    NSString *className = self.functionList[indexPath.row][@"className"];
    UIViewController *subVC = [[NSClassFromString(className) alloc] init];
    subVC.title = self.functionList[indexPath.row][@"title"];
    [self.navigationController pushViewController:subVC animated:NO];
}

#pragma mark - getter & setter
-(NSArray *)functionList {
    if (_functionList == nil) {
        NSString *name = [MAIN_BUNDLE pathForResource:@"functionName.json" ofType:nil];
        NSData *data = [NSData dataWithContentsOfFile:name];
        _functionList = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    }
    return _functionList;
}

- (UIButton *)customButton {
    if (!_customButton) {
        _customButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [_customButton setTitle:@"初始化SDK" forState:UIControlStateNormal];
        [_customButton setTitle:@"初始化SDK" forState:UIControlStateHighlighted];
        [_customButton.titleLabel setFont:[UIFont systemFontOfSize:17]];
        [_customButton setFrame:CGRectMake(0, 3, 69, 20)];
        [_customButton addTarget:self action:@selector(clickCustomButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _customButton;
}
@end
