package partisan.weforge.xyz.pulse

import android.content.Context
import android.graphics.*
import android.view.View
import kotlin.random.Random

class MatrixRainView(context: Context) : View(context) {
    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        color = Color.GREEN
        textSize = 5f * resources.displayMetrics.density
        typeface = Typeface.MONOSPACE
    }

    private val charset = "01アイウエオカキクケコ".toCharArray()
    private val random = Random
    private var columns = 0
    private lateinit var yOffsets: IntArray

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        columns = w / paint.textSize.toInt()
        yOffsets = IntArray(columns) { random.nextInt(h) }
    }

    override fun onDraw(canvas: Canvas) {
        // drawColor with transparent clear instead of black
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR)

        for (i in 0 until columns) {
            val x = i * paint.textSize
            val y = yOffsets[i].toFloat()
            val char = charset[random.nextInt(charset.size)]

            paint.alpha = 255
            canvas.drawText(char.toString(), x, y, paint)

            paint.alpha = 100
            canvas.drawText(char.toString(), x, y - paint.textSize, paint)

            yOffsets[i] += paint.textSize.toInt()
            if (yOffsets[i] > height) {
                yOffsets[i] = 0
            }
        }
        postInvalidateDelayed(50)
    }
}
