package com.xiaoyudesign.rnupdate;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class UpdateDownload {

    public static void download(UpdateDownloadParams params) throws Exception {
        if (params == null) {
            throw new NullPointerException("UpdateDownloadParams 不能为空");
        }

        String url = params.url;
        File outputFile = params.outputFile;
        UpdateDownloadParams.DownloadProgressCallback downloadProgressCallback = params.downloadProgressCallback;

        if(downloadProgressCallback == null) {
            throw new NullPointerException("请指定下载回调");
        }

        if(url == null || url.isEmpty()) {
            downloadProgressCallback.onDownloadStatus(UpdateDownloadParams.DownloadStatus.DOWNLOAD_PARAMS_NOT_EMPTY, "下载参数 {url} 不能为空");
            return;
        }
        if(outputFile == null) {
            downloadProgressCallback.onDownloadStatus(UpdateDownloadParams.DownloadStatus.DOWNLOAD_PARAMS_NOT_EMPTY, "下载参数 {outputFile} 不能为空");
            return;
        }

        // 提前创建输出文件父目录（避免文件路径不存在导致写入失败）
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            boolean mkdirsSuccess = parentDir.mkdirs();
            if (!mkdirsSuccess) {
                downloadProgressCallback.onDownloadStatus(
                        UpdateDownloadParams.DownloadStatus.DOWNLOAD_FAILED,
                        "无法创建文件父目录：" + parentDir.getAbsolutePath()
                );
                return;
            }
        }

        HttpURLConnection connection = null;
        BufferedInputStream input = null;
        FileOutputStream output = null;

        try {
            URL httpUrl = new URL(url);
            connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setConnectTimeout(params.timeout); // 增加超时时间
            connection.setReadTimeout(params.readTimeout);
            connection.setRequestMethod("GET");
            connection.connect();

            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                downloadProgressCallback.onDownloadStatus(UpdateDownloadParams.DownloadStatus.DOWNLOAD_FAILED, "下载失败："+ "code: " + connection.getResponseCode()+", message: "+ connection.getResponseMessage());
                return;
            }

            int fileLength = connection.getContentLength();
            input = new BufferedInputStream(connection.getInputStream());
            output = new FileOutputStream(outputFile);

            byte[] buffer = new byte[8192];
            int len;
            long total = 0;
            int lastProgress = 0;

            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
                total += len;
                if (fileLength > 0) {
                    int progress = (int) (total * 100 / fileLength);
                    if (progress != lastProgress) {
                        lastProgress = progress;
                        downloadProgressCallback.onDownloadProgress(total, fileLength, progress);
                        // 回调下载中状态（可选）
                        downloadProgressCallback.onDownloadStatus(UpdateDownloadParams.DownloadStatus.DOWNLOADING, null);
                    }
                } else {
                    // 总大小未知时，进度传 -1，仅反馈已下载大小
                    downloadProgressCallback.onDownloadProgress(total, fileLength, -1);
                    downloadProgressCallback.onDownloadStatus(UpdateDownloadParams.DownloadStatus.DOWNLOADING, null);
                }
            }

            // 强制补全 100% 进度（避免整除导致进度未到 100）
            if (fileLength > 0) {
                downloadProgressCallback.onDownloadProgress(fileLength, fileLength, 100);
            }

            output.close();
            input.close();
            connection.disconnect();

            downloadProgressCallback.onDownloadStatus(UpdateDownloadParams.DownloadStatus.DOWNLOAD_SUCCESS, null);
            downloadProgressCallback.onDownloadComplete();
        } catch (Exception e) {
            // 10. 异常捕获与回调
            downloadProgressCallback.onDownloadStatus(
                    UpdateDownloadParams.DownloadStatus.DOWNLOAD_FAILED,
                    "下载异常：" + e.getMessage()
            );
            throw e;
        } finally {
            try {
                if (output != null) {
                    output.close();
                }
                if (input != null) {
                    input.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
