package com.performancecoachlab.posedetection.camera

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.UIKitViewController
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import platform.Foundation.NSNotificationCenter
import platform.UIKit.UIDeviceOrientationDidChangeNotification

@Composable
fun CameraPreview(
    modifier: Modifier,
    onCameraControllerReady: (CameraEngine) -> Unit
) {

    val cameraEngine = remember {
        CameraEngine()
    }
    LifecycleEventEffect(Lifecycle.Event.ON_STOP) {
        // Stops camera when going to background
        cameraEngine.stopSession()
    }
    LifecycleEventEffect(Lifecycle.Event.ON_RESUME) {
        // Resumes the camera when coming back from background
        cameraEngine.startSession()
    }

    LaunchedEffect(cameraEngine) {
        onCameraControllerReady(cameraEngine)
    }

    DisposableEffect(Unit) {
        val notificationCenter = NSNotificationCenter.defaultCenter
        val observer = notificationCenter.addObserverForName(
            UIDeviceOrientationDidChangeNotification,
            null,
            null
        ) { _ ->
            cameraEngine.getCameraPreviewLayer()?.connection?.videoOrientation =
                cameraEngine.currentVideoOrientation()
        }

        onDispose {
            notificationCenter.removeObserver(observer)
        }
    }

    UIKitViewController(
        factory = { cameraEngine },
        modifier = modifier,
    )
}
