package de.ladkau.schwertundmagieonpebblecompanionapp

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Rect
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.nio.ByteBuffer

/**
 * Renders the VICE 320×200 ARGB framebuffer into a SurfaceView,
 * scaled to fill the view while keeping the 8:5 aspect ratio.
 */
class C64DisplayView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null
) : SurfaceView(context, attrs), SurfaceHolder.Callback {

    private val bitmap = Bitmap.createBitmap(320, 200, Bitmap.Config.ARGB_8888)
    private val pixelBuf: ByteBuffer = ByteBuffer.allocateDirect(320 * 200 * 4)
    private val srcRect = Rect(0, 0, 320, 200)
    private var dstRect = Rect()

    init {
        holder.addCallback(this)
    }

    /** Called from the emulator thread after every runFrame(). */
    fun updateFrame(engine: C64Engine) {
        if (!holder.surface.isValid) return

        pixelBuf.rewind()
        engine.getVideoBuffer(pixelBuf)
        pixelBuf.rewind()
        bitmap.copyPixelsFromBuffer(pixelBuf)

        val canvas: Canvas = try { holder.lockCanvas() ?: return } catch (_: Exception) { return }
        try {
            canvas.drawBitmap(bitmap, srcRect, dstRect, null)
        } finally {
            holder.unlockCanvasAndPost(canvas)
        }
    }

    override fun surfaceCreated(h: SurfaceHolder) = recalcDst()
    override fun surfaceChanged(h: SurfaceHolder, f: Int, w: Int, h2: Int) = recalcDst()
    override fun surfaceDestroyed(h: SurfaceHolder) {}

    private fun recalcDst() {
        val vw = width.toFloat()
        val vh = height.toFloat()
        val scale = minOf(vw / 320f, vh / 200f)
        val sw = (320 * scale).toInt()
        val sh = (200 * scale).toInt()
        val ox = ((vw - sw) / 2).toInt()
        val oy = ((vh - sh) / 2).toInt()
        dstRect = Rect(ox, oy, ox + sw, oy + sh)
    }
}
