//
//  HWMSetProxyController.m
//  HWMUISDKNativeDemo
//
//  Created by 江万里 on 2022/1/18.
//  Copyright © 2022 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "HWMSetProxyController.h"
#import "HWMInputView.h"
#import <HWMUISDK/HWMUISDK.h>
#import "NSViewController+HWMNavigation.h"


@interface HWMSetProxyController ()

@property (nonatomic, strong) NSButton *noneBtn;
@property (nonatomic, strong) NSButton *useProxyBtn;

/// 服务器地址
@property (nonatomic, strong) HWMInputView *serverView;
/// 端口号
@property (nonatomic, strong) HWMInputView *portView;

/// 账号
@property (nonatomic, strong) HWMInputView *accountView;
/// 密码
@property (nonatomic, strong) HWMInputView *passwordView;

@property (nonatomic, strong) NSButton *confirmBtn;

@property (nonatomic, assign) BOOL useProxy;

@end

@implementation HWMSetProxyController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    self.useProxy = NO;
    [self useProxyChanged:self.useProxy];
    [self getSystemProxyAddress];
    // Do view setup here.
}

- (void)setupUI {
    [self.view addSubview:self.noneBtn];
    [self.view addSubview:self.useProxyBtn];
    
    [self.view addSubview:self.serverView];
    [self.view addSubview:self.portView];
    [self.view addSubview:self.accountView];
    [self.view addSubview:self.passwordView];
    [self.view addSubview:self.confirmBtn];
    
    [self.noneBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(70);
        make.leading.offset(200);
    }];
    
    [self.useProxyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(70);
        make.trailing.offset(-200);
    }];
    
    [self.serverView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(120);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(300);
    }];
    
    [self.portView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.serverView.mas_bottom);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(300);
    }];
    
    [self.accountView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.portView.mas_bottom);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(300);
    }];
    
    [self.passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.accountView.mas_bottom);
        make.centerX.equalTo(self.view);
        make.height.mas_equalTo(50);
        make.width.mas_equalTo(300);
    }];
    
    [self.confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.passwordView.mas_bottom).offset(30);
        make.height.mas_equalTo(35);
        make.width.mas_equalTo(250);
    }];
    
}


- (void)buttonClicked:(NSButton *)btn{
    self.useProxy = btn.tag;
    [self useProxyChanged:self.useProxy];
}

- (void)useProxyChanged:(BOOL)useProxy{
    self.serverView.hidden = !useProxy;
    self.portView.hidden = !useProxy;
    self.accountView.hidden = !useProxy;
    self.passwordView.hidden = !useProxy;
    
    if (useProxy) {
        [self setSystemProxy];
    }
}


- (void)confirmBtnClick{
    HWMProxyInfo *proxyInfo = [[HWMProxyInfo alloc] init];
    if (self.useProxy) {
        NSString *server = self.serverView.textField.stringValue;
        NSString *port = self.portView.textField.stringValue;
        if (server.length == 0) {
            [HWMConsoleManager shareInstance].console = @"please enter server address.";
            return;
        }
        
        if (port.length == 0) {
            [HWMConsoleManager shareInstance].console = @"please enter server port.";
            return;
        }
        proxyInfo.proxyUri = server;
        proxyInfo.proxyPort = [port integerValue];
        proxyInfo.userName = self.accountView.textField.stringValue;
        proxyInfo.password = self.passwordView.textField.stringValue;
    } else {
        proxyInfo.proxyUri = @"";
        proxyInfo.proxyPort = 0;
        proxyInfo.userName = @"";
        proxyInfo.password = @"";
    }
    
    if (@available(macOS 10.13, *)) {
        [[HWMSdk getPrivateApi] setProxyWithProxyInfo:proxyInfo];
        [HWMConsoleManager shareInstance].console = @"set proxy success";
    } else {
        [HWMConsoleManager shareInstance].console = @"need macOS 10.13 and above";
        // Fallback on earlier versions
    }
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.customNavigationController popViewControllerAnimated:YES];
    });

    
    
}

#pragma mark - Lazy
- (NSButton *)noneBtn {
    if (!_noneBtn) {
        _noneBtn = [[NSButton alloc] init];
        _noneBtn.bordered = NO;
        _noneBtn.font = [NSFont systemFontOfSize:12];
        _noneBtn.bezelStyle = NSBezelStyleRegularSquare;
        _noneBtn.state = NSControlStateValueOn;
        [_noneBtn setButtonType:NSButtonTypeRadio];
        [_noneBtn setTitle:@"不使用代理"];
        _noneBtn.target = self;
        _noneBtn.action = @selector(buttonClicked:);
        _noneBtn.tag = 0;
    }
    return _noneBtn;
}

- (NSButton *)useProxyBtn {
    if (!_useProxyBtn) {
        _useProxyBtn = [[NSButton alloc] init];
        _useProxyBtn.bordered = NO;
        _useProxyBtn.font = [NSFont systemFontOfSize:12];
        _useProxyBtn.bezelStyle = NSBezelStyleRegularSquare;
        _useProxyBtn.state = NSControlStateValueOff;
        [_useProxyBtn setButtonType:NSButtonTypeRadio];
        [_useProxyBtn setTitle:@"手动设置代理"];
        _useProxyBtn.target = self;
        _useProxyBtn.action = @selector(buttonClicked:);
        _useProxyBtn.tag = 1;
    }
    return _useProxyBtn;
}

- (HWMInputView *)serverView {
    if (!_serverView) {
        _serverView = [[HWMInputView alloc] init];
        _serverView.title = @"服务器地址:";
        _serverView.placeholder = @"请输入代理服务器地址";
    }
    return _serverView;
}

- (HWMInputView *)portView {
    if (!_portView) {
        _portView = [[HWMInputView alloc] init];
        _portView.title = @"端口号:       ";
        _portView.placeholder = @"请输入代理服务器端口";
    }
    return _portView;
}

- (HWMInputView *)accountView {
    if (!_accountView) {
        _accountView = [[HWMInputView alloc] init];
        _accountView.title = @"账号:           ";
        _accountView.placeholder = @"代理服务器账号";
    }
    return _accountView;
}

- (HWMInputView *)passwordView {
    if (!_passwordView) {
        _passwordView = [[HWMInputView alloc] init];
        _passwordView.title = @"密码:           ";
        _passwordView.placeholder = @"代理服务器密码";
    }
    return _passwordView;
}

- (NSButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [NSButton buttonWithTitle:@"确定" font:nil fontColor:[NSColor whiteColor] target:self action:@selector(confirmBtnClick)];
        _confirmBtn.layer.backgroundColor = [NSColor colorWithRGB:0x0D94FF].CGColor;
        _confirmBtn.layer.cornerRadius = 4.0;
        _confirmBtn.layer.masksToBounds = YES;
    }
    return _confirmBtn;
}

- (void)setSystemProxy {
    NSString *systemProxy = [self getSystemProxyAddress];
    if (systemProxy.length > 0) {
        self.serverView.textField.stringValue = [self getSystemProxyAddress];
        self.portView.textField.stringValue = [NSString stringWithFormat:@"%lu", [self getSystemProxyPort]];
    }
}

- (NSString *)getSystemProxyAddress{
    NSDictionary *proxyDic = CFBridgingRelease(SCDynamicStoreCopyProxies(NULL));
    NSString *proxyAddress = @"";
    if ([proxyDic[@"HTTPEnable"] boolValue]) {
        proxyAddress = proxyDic[@"HTTPProxy"];
    } else if ([proxyDic[@"HTTPSEnable"] boolValue]) {
        proxyAddress = proxyDic[@"HTTPSProxy"];
    }
    return proxyAddress;
}

- (NSUInteger)getSystemProxyPort {
    NSDictionary *proxyDic = CFBridgingRelease(SCDynamicStoreCopyProxies(NULL));
    NSUInteger port = 0;
    if ([proxyDic[@"HTTPEnable"] boolValue]) {
        port = [proxyDic[@"HTTPPort"] unsignedIntegerValue];
    } else if ([proxyDic[@"HTTPSEnable"] boolValue]) {
        port = [proxyDic[@"HTTPSPort"] unsignedIntegerValue];
    }
    return port;
}

@end
