package com.gensee.multi_instance.utils

import android.Manifest
import android.content.ContentResolver
import android.content.ContentValues
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.core.content.ContextCompat
import java.io.BufferedReader
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStreamReader

/**
 *  author : guohaonan
 *  date : 2024/3/13 13:37
 *  description :
 */
object FileHelper {

    private const val TAG = "FileHelper"

    fun writeTextToSdCard(context: Context, fileName: String, text: String): Boolean {
        val resolver: ContentResolver = context.contentResolver
        val contentValues = ContentValues().apply {
            put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
            put(MediaStore.MediaColumns.MIME_TYPE, "application/json")
            put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS)
        }
        val uri = resolver.insert(MediaStore.Files.getContentUri("external"), contentValues)
        uri?.let { fileUri ->
            try {
                resolver.openOutputStream(fileUri)?.use { outputStream ->
                    outputStream.write(text.toByteArray())
                    Log.i(TAG, "Text written to file: $fileUri")
                    return true
                }
            } catch (e: Exception) {
                Log.e(TAG, "Error writing text to file: ${e.message}")
                e.printStackTrace()
            }
        }
        return false
    }

    fun readJsonFromSdCard(context: Context, uri: Uri): String? {
        val resolver: ContentResolver = context.contentResolver

        resolver.query(uri, null, null, null, null)?.use { cursor ->
            if (cursor.moveToFirst()) {
                val uriIndex = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
                val fileUri = MediaStore.Files.getContentUri("external", cursor.getLong(uriIndex))
                resolver.openInputStream(fileUri)?.use { inputStream ->
                    return inputStream.bufferedReader().use { it.readText() }
                }
            }
        }
        return null
    }

    fun readTextFromUri(contentResolver: ContentResolver, uri: Uri): String? {
        val stringBuilder = StringBuilder()
        contentResolver.openInputStream(uri)?.use { inputStream ->
            BufferedReader(InputStreamReader(inputStream)).use { reader ->
                var line: String? = reader.readLine()
                while (line != null) {
                    stringBuilder.append(line)
                    line = reader.readLine()
                }
            }
        }
        return stringBuilder.toString()
    }
}