package com.example.petstoremobile.utils;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

public class FileUtils {
    public static File getFileFromUri(Context context, Uri uri) {
        try {
            if ("content".equals(uri.getScheme())) {
                String authority = uri.getAuthority();
                if (authority != null && authority.equals(context.getPackageName() + ".fileprovider")) {
                    String lastSegment = uri.getLastPathSegment();
                    if (lastSegment != null) {
                        String fileName = lastSegment.contains("/")
                                ? lastSegment.substring(lastSegment.lastIndexOf('/') + 1)
                                : lastSegment;
                        File cachedFile = new File(context.getCacheDir(), fileName);
                        if (cachedFile.exists() && cachedFile.length() > 0) {
                            return cachedFile;
                        }
                    }
                }
            }

            String fileName = getFileName(context, uri);
            if (fileName == null) fileName = "upload_" + System.currentTimeMillis();

            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) return null;

            File tempFile = new File(context.getCacheDir(), fileName);
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.close();
            inputStream.close();
            return tempFile;
        } catch (Exception e) {
            return null;
        }
    }

    public static String getFileName(Context context, Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (index != -1) result = cursor.getString(index);
                }
            }
        }
        if (result == null) {
            result = uri.getPath();
            int cut = result.lastIndexOf('/');
            if (cut != -1) result = result.substring(cut + 1);
        }
        return result;
    }
}