import http from "@ohos:net.http";
import request from "@ohos:request";
import { HttpConfig } from "@normalized:N&&&@yic/http/src/main/ets/core/HttpConfig&1.0.1";
import { Process, ProcessStatus } from "@normalized:N&&&@yic/http/src/main/ets/core/Model&1.0.1";
import { RequestBody } from "@normalized:N&&&@yic/http/src/main/ets/requestbody/RequestBody&1.0.1";
/**
 * @ProjectName : HarmonyUtilSdk
 * @FileName : DownloadRequestBody
 * @Author : yic
 * @Time : 2024/6/20 16:47
 * @Description : 下载请求处理
 */
export default class DownloadRequestBody extends RequestBody {
    protected filePath?: string;
    processCallback?: (process: Process) => void;
    constructor(url: string, filePath?: string) {
        super(url, http.RequestMethod.GET);
        this.filePath = filePath;
    }
    getFilePath(): string {
        return this.filePath;
    }
    setFilePath(filePath: string) {
        this.filePath = filePath;
    }
    setDownloadCallback(downloadCallback: (process: Process) => void) {
        this.processCallback = downloadCallback;
    }
    protected call(): Promise<http.HttpResponse> {
        return new Promise<http.HttpResponse>((resolve, reject) => {
            const url = this.getUrlWithParam();
            request.downloadFile(getContext(this), {
                url: url,
                filePath: this.getFilePath() ? this.getFilePath() : undefined,
                header: this.getHeader() ? { ...this.getHeader() } : undefined
            }).then((task) => {
                let time = new Date().getTime();
                let lastReceivedSize = 0;
                let process = new Process();
                process.path = this.getFilePath();
                //监听下载进度
                task.on('progress', (receivedSize, totalSize) => {
                    if (this.isCancel()) {
                        HttpConfig.getInstance().getTaskDispatch().done(this);
                        task.delete();
                        return;
                    }
                    let now = new Date().getTime();
                    let intervalByteCount = lastReceivedSize === 0 ? 0 : receivedSize - lastReceivedSize;
                    let intervalTime = now - time;
                    lastReceivedSize = receivedSize;
                    time = now;
                    process.currentByteCount = receivedSize;
                    process.totalByteCount = totalSize;
                    process.intervalByteCount = intervalByteCount;
                    process.intervalTime = intervalTime;
                    process.status = ProcessStatus.PROCESSING;
                    this.processCallback && this.processCallback(process);
                });
                task.on('complete', () => {
                    process.status = ProcessStatus.COMPLETED;
                    this.processCallback && this.processCallback(process);
                    const response: http.HttpResponse = {
                        result: JSON.stringify(process),
                        resultType: http.HttpDataType.STRING,
                        responseCode: http.ResponseCode.OK,
                        header: {},
                        cookies: ''
                    };
                    resolve(response);
                });
                task.on('fail', (err) => {
                    process.status = this.isCancel() ? ProcessStatus.CANCEL : ProcessStatus.FAILED;
                    this.processCallback && this.processCallback(process);
                    reject(JSON.stringify(process));
                });
            });
        });
    }
}
