if (!("finalizeConstruction" in ViewPU.prototype)) {
    Reflect.set(ViewPU.prototype, "finalizeConstruction", () => { });
}
interface Index_Params {
    isVpnMode?: boolean;
    innerAccCallback?: AccCallback;
}
import type common from "@ohos:app.ability.common";
import hilog from "@ohos:hilog";
import type ArrayList from "@ohos:util.ArrayList";
import HashMap from "@ohos:util.HashMap";
import { MpAccClient } from "@normalized:N&&&linkboostsdk/Index&1.0.0";
import { AccConfig, AccType } from "@normalized:N&&&linkboostsdk/src/main/ets/linkboost/AccConfig&1.0.0";
import { AccMode } from "@normalized:N&&&linkboostsdk/src/main/ets/linkboost/AccPublicConstants&1.0.0";
import type { LogInfoCallback } from "@normalized:N&&&linkboostsdk/src/main/ets/linkboost/LogInfoCallback&1.0.0";
import type { PathDetail } from "@normalized:N&&&linkboostsdk/src/main/ets/linkboost/PathDetail&1.0.0";
import type { MeasureCallback } from "@normalized:N&&&linkboostsdk/src/main/ets/linkboost/MeasureCallback&1.0.0";
import type { AccCallback } from "@normalized:N&&&linkboostsdk/src/main/ets/linkboost/AccCallback&1.0.0";
import jwt from "@normalized:N&&&@ohos/jsonwebtoken/index&1.0.2";
import type { JwtPayload } from "@normalized:N&&&@ohos/jsonwebtoken/index&1.0.2";
const TAG = "MpAccDemo";
const DOMAIN = 0x0000;
// 获取上下文和客户端实例
let context = getContext(this) as common.UIAbilityContext;
let mpAccClient: MpAccClient = MpAccClient.getInstance(context);
class Index extends ViewPU {
    constructor(parent, params, __localStorage, elmtId = -1, paramsLambda = undefined, extraInfo) {
        super(parent, __localStorage, elmtId, extraInfo);
        if (typeof paramsLambda === "function") {
            this.paramsGenerator_ = paramsLambda;
        }
        this.__isVpnMode = new ObservedPropertySimplePU(true, this, "isVpnMode");
        this.innerAccCallback = {
            onAccSuccess: (ip: string, port: number): void => {
                hilog.info(DOMAIN, TAG, "onAccSuccess:%{public}s port:%{public}d", ip, port);
                // SOCKS5 模式下，加速成功后需要设置代理
                if (!this.isVpnMode) {
                    // TODO: 网络库设置socks5代理，端口和accConfig.socksPort一致
                    hilog.info(DOMAIN, TAG, "SOCKS5模式 加速启动成功 - 需设置搜才开始代理进行切流: 127.0.0.1:xxxx");
                }
                else {
                    hilog.info(DOMAIN, TAG, "VPN模式 加速启动成功");
                }
            },
            onAccFail: (errorCode: number): void => {
                hilog.error(DOMAIN, TAG, "onAccFail errorCode:%{public}d", errorCode);
            },
            onAccDataUpdate: (tRx: number, tTX: number, pathDetails: ArrayList<PathDetail>): void => {
                hilog.info(DOMAIN, TAG, "onAccDataUpdate tRx:%{public}d tTX:%{public}d pathDetails:%{public}s", tRx, tTX, JSON.stringify(pathDetails));
            },
            onSummaryInfoUpdate: (summaryJson: string): void => {
                hilog.info(DOMAIN, TAG, "onSummaryInfoUpdate:%{public}s", JSON.stringify(summaryJson));
            }
        };
        this.setInitiallyProvidedValue(params);
        this.finalizeConstruction();
    }
    setInitiallyProvidedValue(params: Index_Params) {
        if (params.isVpnMode !== undefined) {
            this.isVpnMode = params.isVpnMode;
        }
        if (params.innerAccCallback !== undefined) {
            this.innerAccCallback = params.innerAccCallback;
        }
    }
    updateStateVars(params: Index_Params) {
    }
    purgeVariableDependenciesOnElmtId(rmElmtId) {
        this.__isVpnMode.purgeDependencyOnElmtId(rmElmtId);
    }
    aboutToBeDeleted() {
        this.__isVpnMode.aboutToBeDeleted();
        SubscriberManager.Get().delete(this.id__());
        this.aboutToBeDeletedInternal();
    }
    //  @State isStartMeasure: boolean = false
    private __isVpnMode: ObservedPropertySimplePU<boolean>;
    get isVpnMode() {
        return this.__isVpnMode.get();
    }
    set isVpnMode(newValue: boolean) {
        this.__isVpnMode.set(newValue);
    }
    aboutToDisappear(): void {
        mpAccClient.unregisterAccCallback(this.innerAccCallback);
        // 清理测速回调
        // if (this.isStartMeasure) {
        //   mpAccClient.stopMeasure()
        //   mpAccClient.unregisterMeasureCallback(innerMeasureCallback)
        // }
    }
    aboutToAppear(): void {
        mpAccClient.registerAccCallback(this.innerAccCallback);
        MpAccClient.setAccType(this.isVpnMode ? AccType.VPN : AccType.SOCKS);
        // 设置数据密钥
        //MpAccClient.setDataKey("test-123456", "MTI3NDliZjQyMDcxMzc2MDUxNjUyNTI2MDh0ZXN0MjE3")
        let sign = generateSign("aasc", "HgwLKZi0ECLn1eaJDvL30wbExvMOnonY69KAwSGSMTg=");
        MpAccClient.setSign("app-m839isy91e", sign);
        MpAccClient.setLogInfoCallback(logInfoCallback);
        //mpAccClient.registerMeasureCallback(innerMeasureCallback)
    }
    // 加速回调
    private innerAccCallback: AccCallback;
    initialRender() {
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Column.create();
            Column.height('100%');
            Column.width('100%');
            Column.backgroundColor('#F5F5F5');
        }, Column);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            // 页面标题
            Text.create('加速设置');
            // 页面标题
            Text.fontSize(24);
            // 页面标题
            Text.fontWeight(FontWeight.Bold);
            // 页面标题
            Text.margin({ top: 20, bottom: 20 });
        }, Text);
        // 页面标题
        Text.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            // 配置区域
            Column.create();
            // 配置区域
            Column.width('100%');
            // 配置区域
            Column.padding({ left: 16, right: 16 });
        }, Column);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            // 加速模式切换
            Row.create();
            // 加速模式切换
            Row.width('100%');
            // 加速模式切换
            Row.height(56);
            // 加速模式切换
            Row.padding({ left: 16, right: 16 });
            // 加速模式切换
            Row.backgroundColor('#FFFFFF');
            // 加速模式切换
            Row.borderRadius(12);
        }, Row);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Text.create('加速模式');
            Text.fontSize(16);
            Text.fontColor('#333333');
        }, Text);
        Text.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Blank.create();
        }, Blank);
        Blank.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Text.create(this.isVpnMode ? 'VPN' : 'SOCKS5');
            Text.fontSize(14);
            Text.fontColor(this.isVpnMode ? '#007AFF' : '#FF9500');
            Text.fontWeight(FontWeight.Bold);
            Text.margin({ right: 8 });
        }, Text);
        Text.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Toggle.create({ type: ToggleType.Switch, isOn: this.isVpnMode });
            Toggle.selectedColor('#007AFF');
            Toggle.onChange((isOn: boolean) => {
                this.isVpnMode = isOn;
                hilog.info(DOMAIN, TAG, "切换加速模式: %{public}s", isOn ? "VPN" : "SOCKS");
            });
        }, Toggle);
        Toggle.pop();
        // 加速模式切换
        Row.pop();
        // 配置区域
        Column.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            // 按钮区域
            Column.create();
            // 按钮区域
            Column.width('100%');
            // 按钮区域
            Column.padding({ left: 16, right: 16, top: 20 });
        }, Column);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            // Row() {
            //   Button('开启测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#34C759')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       // 配置测速参数
            //       let measureConfig = new MeasureConfig()
            //        measureConfig.mode = AccMode.REDUNDANT  // 模式
            //        measureConfig.addr = ""  // 测速服务器地址
            //
            //       hilog.info(DOMAIN, TAG, "开始测速, 配置: time=%{public}d, RTT=%{public}d, Loss=%{public}d, quickTime=%{public}d, interval=%{public}d, addr=%{public}s",
            //         measureConfig.time, measureConfig.RTT, measureConfig.Loss, measureConfig.quickTime, measureConfig.interval, measureConfig.addr)
            //
            //       mpAccClient.startMeasure(measureConfig)
            //       this.isStartMeasure = true
            //     })
            //
            //   Button('关闭测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#FF9500')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       hilog.info(DOMAIN, TAG, "停止测速")
            //       mpAccClient.stopMeasure()
            //       this.isStartMeasure = false
            //     })
            // }
            // .width('100%')
            // .justifyContent(FlexAlign.SpaceBetween)
            // .margin({ top: 12 })
            // 开启加速 + 关闭加速
            Row.create();
            // Row() {
            //   Button('开启测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#34C759')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       // 配置测速参数
            //       let measureConfig = new MeasureConfig()
            //        measureConfig.mode = AccMode.REDUNDANT  // 模式
            //        measureConfig.addr = ""  // 测速服务器地址
            //
            //       hilog.info(DOMAIN, TAG, "开始测速, 配置: time=%{public}d, RTT=%{public}d, Loss=%{public}d, quickTime=%{public}d, interval=%{public}d, addr=%{public}s",
            //         measureConfig.time, measureConfig.RTT, measureConfig.Loss, measureConfig.quickTime, measureConfig.interval, measureConfig.addr)
            //
            //       mpAccClient.startMeasure(measureConfig)
            //       this.isStartMeasure = true
            //     })
            //
            //   Button('关闭测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#FF9500')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       hilog.info(DOMAIN, TAG, "停止测速")
            //       mpAccClient.stopMeasure()
            //       this.isStartMeasure = false
            //     })
            // }
            // .width('100%')
            // .justifyContent(FlexAlign.SpaceBetween)
            // .margin({ top: 12 })
            // 开启加速 + 关闭加速
            Row.width('100%');
            // Row() {
            //   Button('开启测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#34C759')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       // 配置测速参数
            //       let measureConfig = new MeasureConfig()
            //        measureConfig.mode = AccMode.REDUNDANT  // 模式
            //        measureConfig.addr = ""  // 测速服务器地址
            //
            //       hilog.info(DOMAIN, TAG, "开始测速, 配置: time=%{public}d, RTT=%{public}d, Loss=%{public}d, quickTime=%{public}d, interval=%{public}d, addr=%{public}s",
            //         measureConfig.time, measureConfig.RTT, measureConfig.Loss, measureConfig.quickTime, measureConfig.interval, measureConfig.addr)
            //
            //       mpAccClient.startMeasure(measureConfig)
            //       this.isStartMeasure = true
            //     })
            //
            //   Button('关闭测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#FF9500')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       hilog.info(DOMAIN, TAG, "停止测速")
            //       mpAccClient.stopMeasure()
            //       this.isStartMeasure = false
            //     })
            // }
            // .width('100%')
            // .justifyContent(FlexAlign.SpaceBetween)
            // .margin({ top: 12 })
            // 开启加速 + 关闭加速
            Row.justifyContent(FlexAlign.SpaceBetween);
            // Row() {
            //   Button('开启测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#34C759')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       // 配置测速参数
            //       let measureConfig = new MeasureConfig()
            //        measureConfig.mode = AccMode.REDUNDANT  // 模式
            //        measureConfig.addr = ""  // 测速服务器地址
            //
            //       hilog.info(DOMAIN, TAG, "开始测速, 配置: time=%{public}d, RTT=%{public}d, Loss=%{public}d, quickTime=%{public}d, interval=%{public}d, addr=%{public}s",
            //         measureConfig.time, measureConfig.RTT, measureConfig.Loss, measureConfig.quickTime, measureConfig.interval, measureConfig.addr)
            //
            //       mpAccClient.startMeasure(measureConfig)
            //       this.isStartMeasure = true
            //     })
            //
            //   Button('关闭测速')
            //     .width('48%')
            //     .height(44)
            //     .fontSize(14)
            //     .fontColor('#FFFFFF')
            //     .backgroundColor('#FF9500')
            //     .borderRadius(22)
            //     .onClick(() => {
            //       hilog.info(DOMAIN, TAG, "停止测速")
            //       mpAccClient.stopMeasure()
            //       this.isStartMeasure = false
            //     })
            // }
            // .width('100%')
            // .justifyContent(FlexAlign.SpaceBetween)
            // .margin({ top: 12 })
            // 开启加速 + 关闭加速
            Row.margin({ top: 12 });
        }, Row);
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Button.createWithLabel('开启加速');
            Button.width('48%');
            Button.height(44);
            Button.fontSize(14);
            Button.fontColor('#FFFFFF');
            Button.backgroundColor('#FF3B30');
            Button.borderRadius(22);
            Button.onClick(() => {
                let accConfig = new AccConfig();
                accConfig.accMode = AccMode.REDUNDANT;
                let nodeMap = new HashMap<string, number>();
                accConfig.accNode = nodeMap;
                if (this.isVpnMode) {
                    MpAccClient.setAccType(AccType.VPN);
                    accConfig.vpnName = "MP_VPN1";
                }
                else {
                    MpAccClient.setAccType(AccType.SOCKS);
                    //TODO: socksPort设置为本地可用端口
                    accConfig.socksPort = 8000;
                }
                mpAccClient.startAcc(accConfig);
            });
        }, Button);
        Button.pop();
        this.observeComponentCreation2((elmtId, isInitialRender) => {
            Button.createWithLabel('关闭加速');
            Button.width('48%');
            Button.height(44);
            Button.fontSize(14);
            Button.fontColor('#FFFFFF');
            Button.backgroundColor('#FF9500');
            Button.borderRadius(22);
            Button.onClick(() => {
                mpAccClient.stopAcc();
            });
        }, Button);
        Button.pop();
        // Row() {
        //   Button('开启测速')
        //     .width('48%')
        //     .height(44)
        //     .fontSize(14)
        //     .fontColor('#FFFFFF')
        //     .backgroundColor('#34C759')
        //     .borderRadius(22)
        //     .onClick(() => {
        //       // 配置测速参数
        //       let measureConfig = new MeasureConfig()
        //        measureConfig.mode = AccMode.REDUNDANT  // 模式
        //        measureConfig.addr = ""  // 测速服务器地址
        //
        //       hilog.info(DOMAIN, TAG, "开始测速, 配置: time=%{public}d, RTT=%{public}d, Loss=%{public}d, quickTime=%{public}d, interval=%{public}d, addr=%{public}s",
        //         measureConfig.time, measureConfig.RTT, measureConfig.Loss, measureConfig.quickTime, measureConfig.interval, measureConfig.addr)
        //
        //       mpAccClient.startMeasure(measureConfig)
        //       this.isStartMeasure = true
        //     })
        //
        //   Button('关闭测速')
        //     .width('48%')
        //     .height(44)
        //     .fontSize(14)
        //     .fontColor('#FFFFFF')
        //     .backgroundColor('#FF9500')
        //     .borderRadius(22)
        //     .onClick(() => {
        //       hilog.info(DOMAIN, TAG, "停止测速")
        //       mpAccClient.stopMeasure()
        //       this.isStartMeasure = false
        //     })
        // }
        // .width('100%')
        // .justifyContent(FlexAlign.SpaceBetween)
        // .margin({ top: 12 })
        // 开启加速 + 关闭加速
        Row.pop();
        // 按钮区域
        Column.pop();
        Column.pop();
    }
    rerender() {
        this.updateDirtyElements();
    }
    static getEntryName(): string {
        return "Index";
    }
}
// 日志回调
let logInfoCallback: LogInfoCallback = {
    onLogInfoUpdate: (tag: string, msg: string): void => {
        //hilog.info(0x0000, tag, "[logInfoCallback]:%s", msg)
    }
};
// 测速回调
let innerMeasureCallback: MeasureCallback = {
    onStartMpAcc: (code: number): void => {
        hilog.info(DOMAIN, TAG, "onStartMpAcc:%{public}d", code);
    },
    onStopMpAcc: (code: number): void => {
        hilog.info(DOMAIN, TAG, "onStopMpAcc:%{public}d", code);
    },
    onStartQos: (code: number): void => {
        hilog.info(DOMAIN, TAG, "onStartQos:%{public}d", code);
    },
    onNoPolicy: (code: number): void => {
        hilog.info(DOMAIN, TAG, "onNoPolicy:%{public}d", code);
    },
    onAccException: (errorCode: number, msg: string): void => {
        hilog.info(DOMAIN, TAG, "onAccException:%{public}d msg:%{public}s", errorCode, msg);
    },
    onRttChanged: (type: number, rtt: number): void => {
        hilog.info(DOMAIN, TAG, "onRttChanged type:%{public}d rtt:%{public}d", type, rtt);
    },
    onAccStateChanged: (state: Number, code: Number): void => {
        hilog.info(DOMAIN, TAG, "onAccStateChanged state:%{public}s code:%{public}s", state.toString(), code.toString());
    }
};
// ==================== Sign 签名生成 ====================
const SIGN_EXPIRE_TIME = 72 * 60 * 60 * 1000; // 过期时间，72小时，单位毫秒
function generateSign(deviceName: string, secretKey: string): string {
    try {
        let exp = Math.floor((Date.now() + SIGN_EXPIRE_TIME) / 1000);
        // 使用库提供的 JwtPayload 类型
        let payload: JwtPayload = {
            deviceName: deviceName,
            exp: exp
        };
        let token: string = jwt.sign(payload, secretKey);
        hilog.info(DOMAIN, TAG, "generateSign success, jwt=%{public}s", token);
        return token;
    }
    catch (e) {
        hilog.error(DOMAIN, TAG, "generateSign error: %{public}s", JSON.stringify(e));
        return "";
    }
}
registerNamedRoute(() => new Index(undefined, {}), "", { bundleName: "com.example.mpaccdemo_harmony", moduleName: "entry", pagePath: "pages/Index", pageFullPath: "entry/src/main/ets/pages/Index", integratedHsp: "false", moduleType: "followWithHap" });
