package io.visus.orbis.feature.orb.ui

import android.view.SurfaceHolder
import android.view.SurfaceView
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import io.visus.orbis.feature.orb.service.OrbRenderService
import kotlinx.coroutines.launch

@Composable
fun OrbSurface(
    renderService: OrbRenderService,
    modifier: Modifier = Modifier
) {
    val coroutineScope = rememberCoroutineScope()

    DisposableEffect(renderService) {
        onDispose {
            renderService.stopRenderLoop()
            renderService.detachSurface()
        }
    }

    AndroidView(
        factory = { context ->
            SurfaceView(context).apply {
                holder.addCallback(object : SurfaceHolder.Callback {
                    override fun surfaceCreated(holder: SurfaceHolder) {
                        // Surface created but dimensions may not be ready
                    }

                    override fun surfaceChanged(
                        holder: SurfaceHolder,
                        format: Int,
                        width: Int,
                        height: Int
                    ) {
                        coroutineScope.launch {
                            renderService.attachSurface(holder.surface, width, height)
                            renderService.startRenderLoop()
                        }
                    }

                    override fun surfaceDestroyed(holder: SurfaceHolder) {
                        renderService.stopRenderLoop()
                        renderService.detachSurface()
                    }
                })
            }
        },
        modifier = modifier
    )
}
