import { findComponentsWithFileUploadAction, getComponentViewBindingId } from "./helpers"

export const getUploadHelperFunctions = (fragment) => {
    if ( findComponentsWithFileUploadAction(fragment).length === 0) return "";

    return `
private val selectFileActivityResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
    if (result.resultCode == Activity.RESULT_OK) {
        val data: Intent? = result.data
        if (data?.data != null) {
            val fileUri: Uri? = data.data
            val filePath = getPathFromUri(requireContext(), fileUri)
            uploadFile(filePath) { fileUrl ->
                if (fileUrl != null) {
                    // Handle the file URL here
                } else {
                    // Handle the error case
                }
            }
        }
    }
}

private fun uploadFile(filePath: String?, onFileUploadResult: (String?) -> Unit) {
    val file = File(filePath)
    val contentType = "multipart/form-data".toMediaTypeOrNull()
    val part = MultipartBody.Part.createFormData(
        "file", file.name, file.asRequestBody(contentType)
    )
    baasViewModel.uploadimages3( part ).observe(viewLifecycleOwner) {
        when (it.status) {
            Status.ERROR -> {
                snackBar(it.message ?: "Something went wrong")
            }
            Status.LOADING -> {}
            Status.SUCCESS -> {
                var fileUrl = it.data?.url
                onFileUploadResult(fileUrl)
            }
        }
    }
}
    `
}

export const getUploadActionListeners = (fragment) => {
    let uploadButtons = findComponentsWithFileUploadAction(fragment)
    if (uploadButtons.length == 0) return "";

    const content = [];
    for (const element of uploadButtons) {
      content.push(`
          binding.${getComponentViewBindingId(element)}.setOnClickWithDebounce {
                val intent = Intent(Intent.ACTION_GET_CONTENT)
                intent.type = "*/*"
                selectFileActivityResult.launch(intent)
            }
      `)
    }
    return content.join("\n")
}

export const getUploadImports = (fragment) => {
    if (findComponentsWithFileUploadAction(fragment).length == 0) return "";

    return `
import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.activity.result.contract.ActivityResultContracts
import com.manaknight.app.utils.FileUtils.getPathFromUri
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody.Companion.asRequestBody
import java.io.File
    `
}