import * as http from "node:http";
import * as https from "node:https"
import path, { join } from "path";
import fs from "fs"
import { app } from "electron";

export function download(fileUrl, filePath=null) {
  if(filePath==null){
    const filename = path.basename(new URL(fileUrl).pathname);
    const updateDir = join(app.getPath('userData'))
    filePath = path.resolve(updateDir, filename);
  }

    return new Promise((resolve, reject) => {
        // 根据 URL 前缀选择不同的下载方式
        const protocol = fileUrl.startsWith('https://') ? https :
                        fileUrl.startsWith('http://') ? http :
                        null;

        if (!protocol) {
            reject(new Error('不支持的 URL 协议'));
            return;
        }

        protocol.get(fileUrl, (response) => {
            // 检查响应状态码
            if (response.statusCode !== 200) {
                reject(new Error(`下载失败，状态码: ${response.statusCode}`));
                return;
            }

            const file = fs.createWriteStream(filePath);

            response.pipe(file);

            file.on('finish', () => {
                file.close();
                resolve(filePath);
            });

            file.on('error', (err) => {
                fs.unlink(filePath, () => {}); // 删除不完整的文件
                reject(err);
            });
        }).on('error', (err) => {
            reject(err);
        });
    });
}
