package com.unibuy.smartdevice.ui.tools;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.Executors;

public class MediaCacheHelper {

    // 取得快取檔（只檢查本地，不下載）
    public static String getCachedPath(Context context, String url) {
        String fileName = getCacheFileName(url);
        File cacheDir = new File(context.getFilesDir(), "ads");
        if (!cacheDir.exists()) cacheDir.mkdirs();
        File file = new File(cacheDir, fileName);

        if (file.exists() && file.length() > 0) {
            Log.d("MediaCache", "Ads使用快取檔: " + file.getAbsolutePath());
            return file.getAbsolutePath();
        }
        Log.d("MediaCache", "Ads快取檔不存在: " + url);
        return null;
    }

    // 在背景下載檔案
    public static String downloadFile(Context context, String url) {
        try {
            String fileName = getCacheFileName(url);
            File cacheDir = new File(context.getFilesDir(), "ads");
            if (!cacheDir.exists()) cacheDir.mkdirs();
            File file = new File(cacheDir, fileName);

            Log.d("MediaCache", "Ads正在下載: " + url);

            URL u = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.connect();

            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                Log.d("MediaCache", "Ads下載失敗: " + url);
                return null;
            }

            InputStream is = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(file);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.close();
            is.close();
            conn.disconnect();

            Log.d("MediaCache", "Ads下載完成: " + file.getAbsolutePath());
            return file.getAbsolutePath();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 產生快取檔名，保留副檔名
    private static String getCacheFileName(String url) {
        String extension = "";
        int dotIndex = url.lastIndexOf('.');
        if (dotIndex != -1) {
            extension = url.substring(dotIndex); // 副檔名包含點
        }
        return url.hashCode() + extension;
    }

    public static void downloadFileAsync(Context context, String url, OnDownloadCompleteListener listener) {
        Executors.newSingleThreadExecutor().execute(() -> {
            String downloaded = downloadFile(context, url);
            new Handler(Looper.getMainLooper()).post(() -> listener.onComplete(downloaded));
        });
    }

    public interface OnDownloadCompleteListener {
        void onComplete(String localPath);
    }

}
