//
//  EZTouchAPViewController.m
//  EZOpenSDKDemo
//
//  Created by JuneCheng on 2023/10/17.
//  Copyright © 2023 hikvision. All rights reserved.
//

#import "EZTouchAPViewController.h"
#import "UIView+Toast.h"
#import "EZConfigTokenInfo.h"
#import "EZAPDevInfo.h"

#define SEARCH_MAX_COUNT (20)

#define SSID          @""  ///< WiFi名称
#define SsidPWD       @""  ///< WiFi密码

@interface EZTouchAPViewController ()

@property (weak, nonatomic) IBOutlet UITextField *tf_ssid;///< WiFi名称
@property (weak, nonatomic) IBOutlet UITextField *tf_password;///< WiFi密码
@property (weak, nonatomic) IBOutlet UITextField *tf_deviceSerial;///< 设备序列号
@property (weak, nonatomic) IBOutlet UITextField *tf_configToken;///< 接触式配网所需的配网token

@property (nonatomic, strong) EZConfigTokenInfo *tokenInfo;
@property (nonatomic, strong) NSTimer *mTimer;
@property (nonatomic, assign) NSInteger searchCount;

@end

@implementation EZTouchAPViewController

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

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"wifi_mode_touch_ap", @"接触式AP配网");
    
    self.tf_ssid.text = SSID;
    self.tf_password.text = SsidPWD;
}

#pragma mark - 接触式配网

/** 获取接触式配网所需的token  */
- (IBAction)getNewAPConfigTokenAction:(id)sender {
    [EZOPENSDK getNewApConfigToken:^(EZConfigTokenInfo * _Nonnull tokenInfo, NSError * _Nonnull error) {
        if (error) {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
            return;
        }
        self.tokenInfo = tokenInfo;
        self.tf_configToken.text = tokenInfo.token;
    }];
}

/** 
 * 接触式配网
 * 必填项：ssid、password、configToken（点击Get NewAPConfigToken按钮获取）
 */
- (IBAction)newAPConfigAction:(id)sender {
    [self stopTimer];
    
    // 步骤1：getNewApConfigToken获取配网所需的tokenInfo；获取成功后手动切换连接设备热点
    NSString *configToken = self.tf_configToken.text;
    if (!configToken || configToken.length == 0) {
        [EZToast show:NSLocalizedString(@"wifi_get_token_first", @"请先获取配网token")];
        return;
    }
    // 步骤2：连接设备热点(手动去设置里连接)
    
    // 步骤3：连接上设备热点后，获取设备的序列号，查询设备配网结果用
    [EZOPENSDK getAccessDeviceInfo:^(EZAPDevInfo * _Nonnull devInfo, NSError * _Nonnull error) {
        if (devInfo) {
            self.tf_deviceSerial.text = devInfo.devSubserial;
            // 步骤4：发起配网请求，设备配网成功后会自动绑定到账号下
            [EZOPENSDK startNewApConfigWithToken:configToken
                                            ssid:self.tf_ssid.text password:self.tf_password.text
                                       lbsDomain:self.tokenInfo.lbsDomain
                               completionHandler:^(EZNewAPConfigStatus status, NSError * _Nonnull error) {
                NSLog(@"EZNewAPConfigStatus result--->%ld", (long)status);
                switch (status) {
                    case EZNewAPConfigStatusConnectSuccess:
                    case EZNewAPConfigStatusUnknow:
                        // 步骤5：设备联网成功或者未知错误(某些型号设备无返回值)的时候发起轮询设备的绑定情况
                        self.mTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(searchDeviceFromService) userInfo:nil repeats:YES];
                        break;
                    case EZNewAPConfigStatusPasswordError:
                        
                        break;
                    case EZNewAPConfigStatusNoAPFound:
                        
                        break;
                        
                    default:
                        break;
                }
            }];
        } else {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
        }
    }];
}

/** 获取设备信息（需要先连接上设备热点）  */
- (IBAction)getDeviceInfoAction:(id)sender {
    [EZOPENSDK getAccessDeviceInfo:^(EZAPDevInfo * _Nonnull devInfo, NSError * _Nonnull error) {
        if (error) {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
            return;
        }
        self.tf_deviceSerial.text = devInfo.devSubserial;
    }];
}

/** 获取WiFi列表（需要先连接上设备热点）  */
- (IBAction)getWiFiListAction:(id)sender {
    [EZOPENSDK getAccessDeviceWifiList:^(NSArray<EZWiFiItemInfo *> * _Nonnull wifiList, NSError * _Nonnull error) {
        if (error) {
            [EZToast show:[NSString stringWithFormat:@"%@", error]];
            return;
        }
        [EZToast show:[NSString stringWithFormat:@"%@", wifiList]];
    }];
}

/** 继续查询 */
- (IBAction)continueSearchAction:(id)sender {
    [self stopTimer];
    [EZOPENSDK queryPlatformBindStatus:self.tf_deviceSerial.text completion:^(BOOL isBindSuccess, NSError * _Nonnull error) {
        if (isBindSuccess) {
            [self showAlertWithTitle:NSLocalizedString(@"wifi_device_bind_success", @"设备已联网成功并绑定账号")];
        } else {
            NSLog(@"error--->%@", error);
        }
    }];
}

/** 停止配网 */
- (IBAction)stopWiFiConfigAction:(id)sender {
    [self stopTimer];
}

- (void)searchDeviceFromService {
    self.searchCount ++;
    if (self.searchCount >= SEARCH_MAX_COUNT) {
        [self.mTimer invalidate];
        self.mTimer = nil;
        return;
    }
    [EZOPENSDK queryPlatformBindStatus:self.tf_deviceSerial.text completion:^(BOOL isBindSuccess, NSError * _Nonnull error) {
        if (isBindSuccess) {
            [self showAlertWithTitle:NSLocalizedString(@"wifi_device_bind_success", @"设备已联网成功并绑定账号")];
            [self stopTimer];
        } else {
            NSLog(@"error--->%@", error);
        }
    }];
}

- (void)stopTimer {
    if (!self.mTimer) {
        return;
    }
    if ([self.mTimer isValid]) {
        [self.mTimer invalidate];
    }
    self.mTimer = nil;
    self.searchCount = 0;
}

@end
