//
//  TKTokenTestHelper.m
//  EZOpenSDKDemo
//
//  Created by junecheng on 2026/8/7.
//  Copyright (c) 2026年 Ezviz. All rights reserved.
//

#import "TKTokenTestHelper.h"
#import "EZOpenSDK.h"
#import "GlobalKit.h"

// JSON 字段名常量
static NSString * const kTKKey_AppKey = @"appKey";
static NSString * const kTKKey_HttpToken = @"httpToken";
static NSString * const kTKKey_DeviceSerial = @"deviceSerial";
static NSString * const kTKKey_DeviceToken = @"deviceToken";
static NSString * const kTKKey_DeviceGlobalToken = @"deviceGlobalToken";
static NSString * const kTKKey_DeviceVideoToken = @"deviceVideoToken";
static NSString * const kTKKey_ChannelNo = @"channelNo";
static NSString * const kTKKey_PreviewStreamToken = @"previewStreamToken";
static NSString * const kTKKey_TalkStreamToken = @"talkStreamToken";
static NSString * const kTKKey_PlaybackStreamToken = @"playbackStreamToken";

@implementation TKTokenTestHelper

+ (void)parseTKTokenBatchJson:(NSString *)jsonStr
              appKeyTextField:(UITextField *)appKeyTextField
               tokenTextField:(UITextField *)tokenTextField
              deviceTextField:(UITextField *)deviceTextField {
    if (jsonStr.length == 0) {
        return;
    }
    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    if (!dict) {
        [EZToast show:@"JSON解析失败，请检查格式"];
        return;
    }
    // 设置appKey和accessToken到输入框
    if (dict[kTKKey_AppKey]) {
        appKeyTextField.text = dict[kTKKey_AppKey];
    }
    if (dict[kTKKey_HttpToken]) {
        tokenTextField.text = dict[kTKKey_HttpToken];
    }
    // 设置指定设备序列号
    if (dict[kTKKey_DeviceSerial]) {
        deviceTextField.text = dict[kTKKey_DeviceSerial];
    }
    // 设置设备级tkToken
    NSString *deviceSerial = dict[kTKKey_DeviceSerial];
    if (deviceSerial && dict[kTKKey_DeviceToken]) {
        [EZOpenSDK setDeviceTokenForDeviceSerial:deviceSerial deviceToken:dict[kTKKey_DeviceToken]];
    }
    // 设置设备通道级tkToken
    if (deviceSerial && dict[kTKKey_DeviceGlobalToken] && dict[kTKKey_DeviceVideoToken]) {
        NSInteger channelNo = [dict[kTKKey_ChannelNo] integerValue];
        [EZOpenSDK setDeviceTokenForDeviceSerial:deviceSerial cameraNo:channelNo deviceGlobalToken:dict[kTKKey_DeviceGlobalToken] deviceVideoToken:dict[kTKKey_DeviceVideoToken]];
    }
    // 设置预览/对讲/回放取流token
    if (dict[kTKKey_PreviewStreamToken]) {
        [GlobalKit shareKit].previewStreamToken = dict[kTKKey_PreviewStreamToken];
    }
    if (dict[kTKKey_TalkStreamToken]) {
        [GlobalKit shareKit].talkStreamToken = dict[kTKKey_TalkStreamToken];
    }
    if (dict[kTKKey_PlaybackStreamToken]) {
        [GlobalKit shareKit].playbackStreamToken = dict[kTKKey_PlaybackStreamToken];
    }
    [EZToast show:@"小权限token批量设置成功"];
}

@end
