package com.atmob.voiceai.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.text.format.Formatter;
import android.webkit.MimeTypeMap;

import com.atmob.common.runtime.ContextUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import atmob.reactivex.rxjava3.annotations.NonNull;

public class FileUtils {


    public static File getVoiceDownloadSaveRootFile() {
        File cacheDir;
        if (Objects.equals(Environment.getExternalStorageState(), Environment.MEDIA_MOUNTED)
                && Environment.getExternalStorageDirectory().canWrite()) {
            cacheDir = ContextUtil.getApplication().getExternalCacheDir();
        } else {
            cacheDir = ContextUtil.getApplication().getCacheDir();
        }
        return cacheDir;
    }
    public static File uriToFileApiQ(@NonNull Uri uri, Context context) {
        File file = null;
        if (uri == null) return file;
        if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
            file = new File(uri.getPath());
        } else if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
            ContentResolver contentResolver = context.getContentResolver();
            String displayName = System.currentTimeMillis() + Math.round((Math.random() + 1) * 1000)
                    + "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(contentResolver.getType(uri));
            try {
                InputStream is = contentResolver.openInputStream(uri);
                File cache = new File(context.getCacheDir().getAbsolutePath(), displayName);
                FileOutputStream fos = new FileOutputStream(cache);
                FileUtils.copy(is, fos);
                file = cache;
                fos.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static void copy(InputStream is, FileOutputStream fos) {
        byte[] buffer = new byte[1024];
        int len;
        try {
            while ((len = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String formatShortBytes(long bytes) {
        Context context = ContextUtil.getContext();
        return Formatter.formatShortFileSize(context, bytes);
    }

    public static long getAudioDurationFromUri(Context context, Uri uri) {
        try {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(context, uri);
            String duration = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
            long durationLong = Long.parseLong(duration);
            return durationLong;
        } catch (Exception ignore) {

        }
        return 0;
    }

    public static long getFileSizeFromUri(Context context, Uri uri) {
        try (Cursor cursor = context.getContentResolver().query(uri, new String[]{DocumentsContract.Document.COLUMN_SIZE}, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getLong(0);
            }
        } catch (Exception ignore) {

        }
        return 0;
    }

    public static String getFileNameFromUri(Context context, Uri uri) {
        try (Cursor cursor = context.getContentResolver().query(uri, new String[]{DocumentsContract.Document.COLUMN_DISPLAY_NAME}, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getString(0);
            }
        } catch (Exception ignore) {

        }
        return "";
    }
}
