package com.siro.siro_driver

import android.content.Intent
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.os.Handler
import android.os.Looper
import androidx.car.app.AppManager
import androidx.car.app.Screen
import androidx.car.app.Session
import androidx.car.app.SurfaceCallback
import androidx.car.app.SurfaceContainer
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner

class MyCarSession : Session(), DefaultLifecycleObserver {
    private var virtualDisplay: VirtualDisplay? = null
    private var presentation: MapPresentation? = null

    override fun onCreateScreen(intent: Intent): Screen {
        lifecycle.addObserver(this)
        
        val appManager = carContext.getCarService(AppManager::class.java)
        appManager.setSurfaceCallback(object : SurfaceCallback {
            override fun onSurfaceAvailable(surfaceContainer: SurfaceContainer) {
                val surface = surfaceContainer.surface ?: return
                val width = surfaceContainer.width
                val height = surfaceContainer.height
                val dpi = surfaceContainer.dpi

                val displayManager = carContext.getSystemService(DisplayManager::class.java)
                virtualDisplay = displayManager.createVirtualDisplay(
                    "CarAppMapDisplay",
                    width,
                    height,
                    dpi,
                    surface,
                    DisplayManager.VIRTUAL_DISPLAY_FLAG_OWN_CONTENT_ONLY
                )

                virtualDisplay?.display?.let { display ->
                    Handler(Looper.getMainLooper()).post {
                        presentation = MapPresentation(carContext, display)
                        presentation?.show()
                    }
                }
            }

            override fun onVisibleAreaChanged(visibleArea: android.graphics.Rect) {
                // تحديث المساحة المرئية إذا لزم الأمر
            }

            override fun onSurfaceDestroyed(surfaceContainer: SurfaceContainer) {
                Handler(Looper.getMainLooper()).post {
                    presentation?.dismiss()
                    presentation = null
                }
                virtualDisplay?.release()
                virtualDisplay = null
            }
        })

        return MyCarScreen(carContext)
    }

    override fun onResume(owner: LifecycleOwner) { presentation?.onResume() }
    override fun onPause(owner: LifecycleOwner) { presentation?.onPause() }
    override fun onDestroy(owner: LifecycleOwner) { presentation?.onDestroy() }
}
