package com.example.myapplication.service;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

public class DownloadService {
    public static boolean saveToDownloads(Context ctx, String srcPath, String displayName, String mime) {
        if (srcPath == null || srcPath.isEmpty()) return false;
        File src = new File(srcPath);
        if (!src.exists()) return false;
        if (displayName == null || displayName.trim().isEmpty()) {
            displayName = src.getName();
        }
        if (mime == null || mime.isEmpty()) mime = guessMime(displayName);

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                ContentResolver resolver = ctx.getContentResolver();
                ContentValues values = new ContentValues();
                values.put(MediaStore.Downloads.DISPLAY_NAME, displayName);
                values.put(MediaStore.Downloads.MIME_TYPE, mime);
                values.put(MediaStore.Downloads.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);
                Uri uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values);
                if (uri == null) return false;
                try (FileInputStream in = new FileInputStream(src);
                     OutputStream out = resolver.openOutputStream(uri)) {
                    if (out == null) return false;
                    byte[] buf = new byte[8192];
                    int len;
                    while ((len = in.read(buf)) != -1) out.write(buf, 0, len);
                    out.flush();
                }
                return true;
            } else {
                File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                if (dir != null && !dir.exists()) dir.mkdirs();
                File dst = new File(dir, displayName);
                try (FileInputStream in = new FileInputStream(src);
                     FileOutputStream out = new FileOutputStream(dst)) {
                    byte[] buf = new byte[8192];
                    int len;
                    while ((len = in.read(buf)) != -1) out.write(buf, 0, len);
                    out.flush();
                }
                return true;
            }
        } catch (Exception e) {
            android.util.Log.e("DownloadService", "saveToDownloads failed", e);
            return false;
        }
    }

    public static String guessMime(String name) {
        String lower = name.toLowerCase();
        if (lower.endsWith(".pdf")) return "application/pdf";
        if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return "image/jpeg";
        if (lower.endsWith(".png")) return "image/png";
        if (lower.endsWith(".txt")) return "text/plain";
        if (lower.endsWith(".doc")) return "application/msword";
        if (lower.endsWith(".docx")) return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        return "application/octet-stream";
    }

    public static boolean saveTextToDownloads(Context ctx, String displayName, String mime, String content) {
        android.net.Uri uri = saveTextToDownloadsReturnUri(ctx, displayName, mime, content);
        return uri != null;
    }

    public static android.net.Uri saveTextToDownloadsReturnUri(Context ctx, String displayName, String mime, String content) {
        if (displayName == null || displayName.trim().isEmpty()) displayName = System.currentTimeMillis() + ".txt";
        if (mime == null || mime.isEmpty()) mime = "text/plain";
        if (content == null) content = "";
        try {
            byte[] data = content.getBytes("UTF-8");
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                android.content.ContentResolver resolver = ctx.getContentResolver();
                android.content.ContentValues values = new android.content.ContentValues();
                values.put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, displayName);
                values.put(android.provider.MediaStore.MediaColumns.MIME_TYPE, mime);
                values.put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, android.os.Environment.DIRECTORY_DOWNLOADS);
                values.put(android.provider.MediaStore.MediaColumns.IS_PENDING, 1);
                android.net.Uri uri = resolver.insert(android.provider.MediaStore.Files.getContentUri("external"), values);
                if (uri == null) return null;
                try (java.io.OutputStream out = resolver.openOutputStream(uri)) {
                    if (out == null) return null;
                    out.write(data);
                    out.flush();
                }
                android.content.ContentValues done = new android.content.ContentValues();
                done.put(android.provider.MediaStore.MediaColumns.IS_PENDING, 0);
                resolver.update(uri, done, null, null);
                return uri;
            } else {
                java.io.File dir = android.os.Environment.getExternalStoragePublicDirectory(android.os.Environment.DIRECTORY_DOWNLOADS);
                if (dir != null && !dir.exists()) dir.mkdirs();
                java.io.File dst = new java.io.File(dir, displayName);
                try (java.io.FileOutputStream out = new java.io.FileOutputStream(dst)) {
                    out.write(data);
                    out.flush();
                }
                return android.net.Uri.fromFile(dst);
            }
        } catch (Exception e) {
            android.util.Log.e("DownloadService", "saveTextToDownloadsReturnUri failed", e);
            return null;
        }
    }
}