//
//  RemoteControlWebViewController.m
//  HWMSDKDemo
//
//  Created by yaolili/ywx577644 on 2023/9/11.
//  Copyright © 2023 HuaWei. All rights reserved.
//

#import "RemoteControlWebViewController.h"
#import <WebKit/WebKit.h>
#import "sys/utsname.h"
#import <HWMUISDK/HWMSdk.h>
#import "LoginManager.h"

@interface RemoteControlWebViewController ()<WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, copy) NSString *urlStr;

@end

@implementation RemoteControlWebViewController

- (instancetype)initWithNonce:(NSString *)nonce code:(NSString *)code isForce:(BOOL)isForce {
    self = [super init];
    if (self) {
        HWMOpenSDKConfig *config = [HWMSdk getSdkConfig];
        NSString *language = @"zh-CN";// 中文：zh-CN 英文：en-US;
        NSString *plistPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"demoEnvConfig" ofType:@"plist"];
        NSMutableDictionary *plistDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
        NSString *loginAddress = [plistDic valueForKey:@"china"];
        if (config.serverAddress && config.serverAddress.length > 0) {
            loginAddress = config.serverAddress;
        }
        NSString *deviceName = @"";
        NSString *deviceID = @"";
        if (![self isLogined]) {
            deviceName = [self deviceName];
            deviceID = [self deviceID];
        }
        self.urlStr = [NSString stringWithFormat:@"https://%@/hcp/#/controller/auth?language=%@&nonce=%@&code=%@&deviceName=%@&deviceId=%@&forceBind=%@", loginAddress, language, nonce, code, deviceName, deviceID, isForce?@"true":@"false"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showLoading];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
    [self.webView loadRequest:urlRequest];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if ([challenge previousFailureCount] == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    } else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
    }
}

- (void)webView:(WKWebView*)webView decidePolicyForNavigationAction:(WKNavigationAction*)navigationAction decisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler
{
    if ([navigationAction.request.URL.absoluteString containsString:@"inappbrowserref_close_url"]) {
        NSLog(@"close web");
        decisionHandler(WKNavigationActionPolicyCancel);
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [self hideLoading];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:self.urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSInteger statusCode = ((NSHTTPURLResponse *)response).statusCode;
        NSLog(@"webViewDidFinishedTrack,statusCode:%ld",(long)statusCode);
    }];
    [dataTask resume];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"web load fail error %@", error);
    [self webviewLoadFail];
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    NSLog(@"webView didFailNavigation %@", error);
    [self webviewLoadFail];
}

- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    NSLog(@"enter webViewWebContentProcessDidTerminate");
    [self webviewLoadFail];
}

- (void)webviewLoadFail {
    [self hideLoading];
    [UIUtil showMessage:@"webview加载失败"];
}

- (WKWebView *)webView {
    if (!_webView) {
        _webView = [[WKWebView alloc] init];
        _webView.navigationDelegate = self;
        [self.view addSubview:_webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
    }
    return _webView;
}

- (BOOL)isLogined {
    return [[LoginManager sharedInstance] hasLogin];
}

- (NSString *)deviceID {
    return [UIDevice currentDevice].identifierForVendor.UUIDString;
}

- (NSString *)deviceName
{
    struct utsname systemInfo;
    uname(&systemInfo);
    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
}

- (void)showLoading {
    [self.activityIndicator startAnimating];
}

- (void)hideLoading {
    [self.activityIndicator stopAnimating];
}


@end
