import fs from "@ohos:file.fs";
import http from "@ohos:net.http";
export class CLVideoManager {
    static async readVideo(url: string): Promise<Uint8Array> {
        return new Promise((resolve, reject) => {
            try {
                if (url.startsWith('http')) {
                    resolve(CLVideoManager.fetchVideoAsUint8Array(url));
                }
                else {
                    const data = CLVideoManager.readLocalVideoAsUint8Array(url);
                    resolve(data);
                }
            }
            catch (e) {
                console.error(e);
                reject(e);
            }
        });
    }
    static readLocalVideoAsUint8Array(filePath: string): Uint8Array {
        // 以只读模式打开
        const file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
        // 获取文件信息（主要是大小）
        const stat = fs.statSync(filePath);
        // 读取文件内容到 ArrayBuffer
        let buffer = new ArrayBuffer(stat.size);
        fs.readSync(file.fd, buffer);
        // 关闭文件
        fs.closeSync(file);
        // 转成 Uint8Array 返回
        return new Uint8Array(buffer);
    }
    static async fetchVideoAsUint8Array(url: string): Promise<Uint8Array> {
        return new Promise((resolve, reject) => {
            let httpRequest = http.createHttp();
            httpRequest.request(url, {
                method: http.RequestMethod.GET,
                expectDataType: http.HttpDataType.ARRAY_BUFFER, // 关键点：期望返回 ArrayBuffer
            }, (err, data) => {
                httpRequest.destroy(); // 用完销毁
                if (err) {
                    reject(err);
                    return;
                }
                try {
                    let buffer: ArrayBuffer = data.result as ArrayBuffer;
                    let uint8Array = new Uint8Array(buffer);
                    resolve(uint8Array);
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
}
