package com.houshan.basa

import io.flutter.embedding.android.FlutterActivity
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import androidx.annotation.NonNull
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.io.FileInputStream
import java.io.OutputStream
import android.net.Uri
import androidx.core.content.FileProvider

class MainActivity: FlutterActivity(){
    private val CHANNEL = "file_channel"

    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "copyToDownloads") {
                val filePath = call.argument<String>("filePath") ?: return@setMethodCallHandler
                val fileName = call.argument<String>("fileName") ?: return@setMethodCallHandler

                val success = copyFileToDownloads(filePath, fileName)
                if (success) {
                    result.success("File copied successfully")
                } else {
                    result.error("FILE_COPY_ERROR", "Failed to copy file", null)
                }
            }
        }


    }

    private fun copyFileToDownloads(filePath: String, fileName: String): Boolean {
        return try {
            val context: Context = applicationContext
            val file = File(filePath)
            if (!file.exists()) return false

            val resolver = context.contentResolver
            val contentValues = ContentValues().apply {
                put(MediaStore.Downloads.DISPLAY_NAME, fileName)
                put(MediaStore.Downloads.MIME_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") // Excel MIME type
                put(MediaStore.Downloads.IS_PENDING, 1)
            }

            val uri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, contentValues)
                ?: return false

            resolver.openOutputStream(uri).use { outputStream ->
                FileInputStream(file).use { inputStream ->
                    inputStream.copyTo(outputStream!!)
                }
            }

            contentValues.clear()
            contentValues.put(MediaStore.Downloads.IS_PENDING, 0)
            resolver.update(uri, contentValues, null, null)

            true
        } catch (e: Exception) {
            Log.e("FileCopy", "Error copying file to downloads", e)
            false
        }
    }


}
