// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.text.style.ReplacementSpan

class RoundedBackgroundSpan(private val bgColour: Int, private val fgColour: Int) :
	ReplacementSpan() {

		companion object {
			const val PADDING = 20  // TODO based on small text, make dependent on eg. em-dash length
		}

	override fun getSize(
		paint: Paint,
		text: CharSequence,
		start: Int,
		end: Int,
		fm: Paint.FontMetricsInt?
	): Int {
		val l = paint.measureText(text, start, end) + PADDING
		if (fm != null) {
			fm.ascent = paint.fontMetrics.ascent.toInt()
			fm.bottom = paint.fontMetrics.bottom.toInt()
			fm.descent = paint.fontMetrics.descent.toInt()
			fm.leading = paint.fontMetrics.leading.toInt()
			fm.top = paint.fontMetrics.top.toInt()
		}
		return l.toInt()
	}

	override fun draw(
		canvas: Canvas,
		text: CharSequence,
		start: Int,
		end: Int,
		x: Float,
		top: Int,
		y: Int,
		bottom: Int,
		paint: Paint
	) {
		val length = paint.measureText(text, start, end) + PADDING
		/*
		Log.i("BackgroundSpan", "x: $x, y: $y, start: $start, end: $end, top: $top, bottom: $bottom")
		Log.i("BackgroundSpan", "text: $text, length: $length")
		Log.i("BackgroundSpan", "fontMetrics:: bottom: ${paint.fontMetricsInt.bottom}, top: ${paint.fontMetricsInt.top}, ascent: ${paint.fontMetricsInt.ascent}, descent: ${paint.fontMetricsInt.descent}, leading: ${paint.fontMetricsInt.leading}")
		Log.i("BackgroundSpan", "fontSpacing: ${paint.fontSpacing}; 1dp=${dpToPixelI(1f)}")
		*/
		val height = y - top
		val rect = RectF(x, top.toFloat()-(height/6), x + length, y.toFloat()+(height/6))
		paint.color = bgColour
		canvas.drawRoundRect(rect, height/4f, height/4f, paint)
		paint.color = fgColour
		paint.textAlign = Paint.Align.CENTER
		canvas.drawText(text, start, end, x + (length / 2), y.toFloat(), paint)
	}
}