package com.photobooth.app

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
import java.util.Random

class FilmGrainView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val random = Random()
    private val paint = Paint().apply {
        style = Paint.Style.FILL
    }

    var intensity: Float = 0f
        set(value) {
            field = value.coerceIn(0f, 1f)
            if (field > 0f) {
                visibility = VISIBLE
                postInvalidateOnAnimation()
            } else {
                visibility = GONE
            }
        }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (intensity <= 0f) return

        val w = width.toFloat()
        val h = height.toFloat()
        if (w <= 0 || h <= 0) return

        // Calculate count based on width, height and intensity
        val grainCount = (w * h * 0.005f * intensity).toInt().coerceIn(200, 5000)
        val maxAlpha = (intensity * 110).toInt().coerceIn(1, 255)

        for (i in 0 until grainCount) {
            val x = random.nextFloat() * w
            val y = random.nextFloat() * h
            val gray = random.nextInt(55) + 100 // [100 - 155] range for cinema film grain look
            val alpha = random.nextInt(maxAlpha)

            paint.color = Color.argb(alpha, gray, gray, gray)
            
            // Draw tiny rectangular grain shapes
            canvas.drawRect(x, y, x + 2.5f, y + 2.5f, paint)
        }

        // Repaint continuously at screen refresh rate to simulate dynamic analog noise
        postInvalidateOnAnimation()
    }
}
