package com.isidroid.c23.ui._component

import android.Manifest
import android.content.pm.PackageManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.platform.LocalContext
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.isidroid.c23.BuildConfig
import java.io.File
import java.util.Objects

@Composable
fun TakePictureComponent(
    hash: String,
    onPictureTaken: (String) -> Unit,
    onPermissionDenied: () -> Unit,
) {
    val context = LocalContext.current
    val file = File.createTempFile(hash, ".jpg")
    val uri = FileProvider.getUriForFile(
        Objects.requireNonNull(context),
        BuildConfig.APPLICATION_ID + ".fileprovider", file
    )
    val hasCameraPermission by remember { mutableStateOf(ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) }
    var capturedImageUri by remember { mutableStateOf(Uri.EMPTY) }
    val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { capturedImageUri = uri }
    val permissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) {
        if (it) cameraLauncher.launch(uri)
        else onPermissionDenied()
    }

    LaunchedEffect(hasCameraPermission, hash) {
        if (!hasCameraPermission)
            permissionLauncher.launch(Manifest.permission.CAMERA)
        else
            cameraLauncher.launch(uri)
    }

    LaunchedEffect(capturedImageUri.path) {
        if (capturedImageUri.path?.isNotEmpty() == true)
            onPictureTaken(capturedImageUri.path.orEmpty())
    }
}