//
//  EZDeviceResultViewController.m
//  EZOpenSDKDemo
//
//  Created by DeJohn Dong on 15/10/28.
//  Copyright © 2015年 Ezviz. All rights reserved.
//

#import "EZDeviceResultViewController.h"
#import "UIAlertController+DeviceVerifyCodeBySerial.h"
#import "EZBusinessTool.h"
#import "MBProgressHUD.h"

#import "EZProbeDeviceInfo.h"
#import "EZWifiConfigViewController.h"
#import "EZWifiTipsViewController.h"

@interface EZDeviceResultViewController ()

@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *indicatorView;
@property (nonatomic, weak) IBOutlet UIImageView *resultImageView;
@property (nonatomic, weak) IBOutlet UIImageView *noWifiImageView;
@property (nonatomic, weak) IBOutlet UIButton *actionButton;
@property (nonatomic, weak) IBOutlet UILabel *resultLabel;
@property (nonatomic, weak) IBOutlet UILabel *statusLabel;

@property (nonatomic,assign) BOOL supportApMode;
@property (nonatomic,assign) BOOL supportSmartMode;
@property (nonatomic,assign) BOOL supportSoundMode;
@property (nonatomic,assign) BOOL supportApHttpMode;
@property (nonatomic,assign) BOOL supportWiFi5G;///< AP配网是否支持5G频段

@end

@implementation EZDeviceResultViewController

#pragma mark - Life Cycle

- (instancetype)init {
    if (self = [super init]) {
        self = [EZStoryBoardTool getViewController:@"AddDevice" andIdentifier:@"EZDeviceResultViewController"];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"ad_result_title", @"结果");
    
    self.statusLabel.hidden = YES;
    self.actionButton.hidden = YES;
    
    [self searchDeviceReq];
}

#pragma mark - Action Methods

- (IBAction)nextAction:(id)sender {
    NSString *actionButtonTitle = self.actionButton.titleLabel.text;
    if ([actionButtonTitle isEqualToString:NSLocalizedString(@"ad_connect_net", @"连接网络")]) {
        [self performSegueWithIdentifier:@"go2WifiTips" sender:nil];
    } else if ([actionButtonTitle isEqualToString:NSLocalizedString(@"ad_add",@"添加")]) {
        if ([GlobalKit shareKit].deviceVerifyCode != nil) {
            [self addDeviceReq];
        } else {
            [self showSetPassword];
        }
    } else {// 重试
        [self searchDeviceReq];
    }
}

#pragma mark - Request

- (void)searchDeviceReq {
    [self.indicatorView startAnimating];
    self.indicatorView.hidden = NO;
    self.actionButton.hidden = YES;
    self.noWifiImageView.hidden = YES;
    
    self.resultLabel.text = NSLocalizedString(@"ad_get_device_info_msg",@"正在查询设备信息，请稍后...");

    [EZOPENSDK probeDeviceInfo:[GlobalKit shareKit].deviceSerialNo
                    deviceType:[GlobalKit shareKit].deviceModel
                    completion:^(EZProbeDeviceInfo *deviceInfo, NSError *error) {
        [self.indicatorView stopAnimating];
        self.indicatorView.hidden = YES;
        self.resultImageView.hidden = NO;
        self.resultLabel.text = [GlobalKit shareKit].deviceSerialNo;

        if (error) {
            if (error.code == EZ_HTTPS_DEVICE_ADDED_MYSELF ||
                error.code == EZ_HTTPS_DEVICE_ONLINE_ADDED ||
                error.code == EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED_MYSELF) {
                self.statusLabel.textColor = [UIColor blackColor];
                self.statusLabel.text = NSLocalizedString(@"ad_already_added",@"您已添加过此设备");
                self.statusLabel.hidden = NO;
            } else if (error.code == EZ_HTTPS_DEVICE_ONLINE_IS_ADDED || error.code == EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED) {
                self.statusLabel.textColor = [UIColor blackColor];
                self.statusLabel.text = NSLocalizedString(@"ad_added_by_others",@"此设备已被别人添加");
                self.statusLabel.hidden = NO;
            } else if (error.code == EZ_HTTPS_DEVICE_NOT_EXISTS) {
                self.statusLabel.textColor = [UIColor blackColor];
                self.statusLabel.text = NSLocalizedString(@"ad_not_exist",@"此设备不存在");
                self.statusLabel.hidden = NO;
            } else if (error.code == EZ_HTTPS_DEVICE_OFFLINE_NOT_ADDED) {
                self.statusLabel.hidden = NO;
                self.actionButton.hidden = NO;
                if (deviceInfo) {
                    self.supportApMode = deviceInfo.supportAP == 2;
                    self.supportSmartMode = deviceInfo.supportWifi == 3;
                    self.supportSoundMode = deviceInfo.supportSoundWave == 1;
                    self.supportApHttpMode = deviceInfo.supportAPType == 1;
                    self.supportWiFi5G = deviceInfo.support5GWiFi;
                    // 记录该设备热点前缀
                    [GlobalKit shareKit].WiFiConfigPrefix = [EZBusinessTool getWiFiConfigPrefix:deviceInfo.deviceHotSpot];
                } else {
                    // 查不到能力级则根据设备灯来判断配网模式
                    self.supportApMode = YES;
                    self.supportSmartMode = YES;
                    self.supportSoundMode = YES;
                }
                [self.actionButton setTitle:NSLocalizedString(@"ad_connect_net", @"连接网络") forState:UIControlStateNormal];
            } else {
                self.resultLabel.text = [NSString stringWithFormat:NSLocalizedString(@"get_info_fail", @"查询失败，错误码：%d"), error.code];
                self.noWifiImageView.hidden = NO;
                self.resultImageView.hidden = YES;
                self.actionButton.hidden = NO;
                [self.actionButton setTitle:NSLocalizedString(@"retry", @"重试") forState:UIControlStateNormal];
            }
            
            return;
        }
        self.actionButton.hidden = NO;
        [self.actionButton setTitle:NSLocalizedString(@"ad_add",@"添加") forState:UIControlStateNormal];
    }];

}

/** 添加设备 */
- (void)addDeviceReq {
    __weak MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = NSLocalizedString(@"ad_adding_msg", @"正在添加，请稍候...");
    [EZOPENSDK addDevice:[GlobalKit shareKit].deviceSerialNo
              verifyCode:[GlobalKit shareKit].deviceVerifyCode
              completion:^(NSError *error) {
                  [hud hide:YES];
                  [self deviceAddErrorHandle:error];
              }];
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([[segue destinationViewController] isKindOfClass:[EZWifiConfigViewController class]]) {
        ((EZWifiConfigViewController *)[segue destinationViewController]).isAddDeviceSuccessed = YES;
    } else if ([[segue destinationViewController] isKindOfClass:[EZWifiTipsViewController class]]) {
        EZWifiTipsViewController *vc = (EZWifiTipsViewController *)[segue destinationViewController];
        vc.supportApMode = self.supportApMode;
        vc.supportSmartMode = self.supportSmartMode;
        vc.supportSoundMode = self.supportSoundMode;
        vc.supportApHttpMode = self.supportApHttpMode;
        vc.supportWiFi5G = self.supportWiFi5G;
    }
}

#pragma mark - Custom Methods

- (void)deviceAddErrorHandle:(NSError *)error {
    if (!error) {
        [self performSegueWithIdentifier:@"go2WifiResult" sender:nil];
        return;
    }
    if (error.code == EZ_HTTPS_DEVICE_VALICATECODE_ERROR) {
        [self showRetry];
    } else if (error.code == EZ_HTTPS_DEVICE_ADDED_MYSELF ||
               error.code == EZ_HTTPS_DEVICE_ONLINE_ADDED ||
               error.code == EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED_MYSELF) {
        [self.view makeToast:NSLocalizedString(@"ad_already_added",@"您已添加过此设备") duration:3 position:@"center"];
    } else if (error.code == EZ_HTTPS_DEVICE_ONLINE_IS_ADDED || error.code == EZ_HTTPS_DEVICE_OFFLINE_IS_ADDED) {
        [self.view makeToast:NSLocalizedString(@"ad_added_by_others",@"此设备已被别人添加") duration:3 position:@"center"];
    } else {
        [self.view makeToast:[NSString stringWithFormat:@"%@%ld", NSLocalizedString(@"wifi_add_fail", @"添加失败，错误码："), (long)error.code] duration:3 position:@"center"];
    }
}

#pragma mark - ValidateCode Methods

- (void)showSetPassword {
    [UIAlertController showAlertWithDeviceSerial:[GlobalKit shareKit].deviceVerifyCode title:NSLocalizedString(@"device_input_vierify_code", @"请输入设备验证码") message:@"" confirmBlock:^(NSString * _Nonnull code) {
        [self addDeviceReq];
    } cancelBlock:^{
        
    }];
}

- (void)showRetry {
    [UIAlertController showDeviceSerialRetryAlert:^{
        [self showSetPassword];
    }];
}

@end
