package com.mogo.skin.net;

import android.os.AsyncTask;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class DownloadManager {
    private static final int BUFFER_SIZE = 1024 * 1024; // 1MB
    private static final Map<String, DownloadTask> activeDownloads = new HashMap<>();
    private String downloadUrl;
    private File outputDir;
    private File outputFile;
    private DownloadListener listener;
    private long downloadedLength;
    private boolean isCancelled = false;

    public interface DownloadListener {
        void onProgressUpdate(int progress);
        void onDownloadSuccess();
        void onDownloadFailed(Exception e);
        void onAlreadyDownloading(String url);
    }

    public DownloadManager(String url, File directory, DownloadListener listener) {
        this.downloadUrl = url;
        this.outputDir = directory;
        this.listener = listener;
        this.outputFile = new File(outputDir, getFileNameFromUrl(url));

        // 确保输出目录存在
        if (!outputDir.exists()) {
            outputDir.mkdirs();
        }

        // 如果文件不存在，则创建空文件
        if (!outputFile.exists()) {
            try {
                outputFile.createNewFile();
            } catch (IOException e) {
                if (listener != null) {
                    listener.onDownloadFailed(e);
                }
                return;
            }
        }

        this.downloadedLength = outputFile.length();
    }

    private String getFileNameFromUrl(String url) {
        return url.substring(url.lastIndexOf('/') + 1);
    }

    public void startDownload() {
        if (activeDownloads.containsKey(downloadUrl)) {
            if (listener != null) {
                listener.onAlreadyDownloading(downloadUrl);
            }
            return;
        }

        DownloadTask task = new DownloadTask();
        activeDownloads.put(downloadUrl, task);
        task.execute(downloadUrl);
    }

    public void cancelDownload() {
        isCancelled = true;
        DownloadTask task = activeDownloads.get(downloadUrl);
        if (task != null) {
            task.cancel(true);
            activeDownloads.remove(downloadUrl);
        }
    }

    private class DownloadTask extends AsyncTask<String, Integer, Boolean> {
        @Override
        protected Boolean doInBackground(String... urls) {
            try (RandomAccessFile raf = new RandomAccessFile(outputFile, "rw")) {
                URL url = new URL(urls[0]);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(15000); // 15 seconds
                connection.setReadTimeout(15000); // 15 seconds
                if (downloadedLength > 0) {
                    connection.setRequestProperty("Range", "bytes=" + downloadedLength + "-");
                }
                InputStream in = connection.getInputStream();
                byte[] buffer = new byte[BUFFER_SIZE];
                int read;
                while ((read = in.read(buffer)) != -1 && !isCancelled) {
                    raf.write(buffer, 0, read);
                    downloadedLength += read;
                    publishProgress((int) (downloadedLength * 100 / connection.getContentLengthLong()));
                }
                return !isCancelled;
            } catch (IOException e) {
                if (!isCancelled) {
                    if (listener != null) {
                        listener.onDownloadFailed(e);
                    }
                }
                return false;
            } finally {
                activeDownloads.remove(downloadUrl);
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (listener != null) {
                listener.onProgressUpdate(values[0]);
            }
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result && listener != null) {
                listener.onDownloadSuccess();
            }
        }
    }
}