package com.isidroid.ui.maps.ext

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.text.TextPaint
import androidx.annotation.ColorInt
import androidx.core.content.ContextCompat
import com.google.android.gms.maps.model.BitmapDescriptor
import com.google.android.gms.maps.model.BitmapDescriptorFactory
import com.isidroid.ui.maps.R

internal fun fromSvg(context: Context, resId: Int): BitmapDescriptor {
    val vectorDrawable: Drawable = ContextCompat.getDrawable(context, resId)!!
    vectorDrawable.setBounds(
        0,
        0,
        vectorDrawable.intrinsicWidth,
        vectorDrawable.intrinsicHeight
    )
    val bitmap = Bitmap.createBitmap(
        vectorDrawable.intrinsicWidth,
        vectorDrawable.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(bitmap)
    vectorDrawable.draw(canvas)
    return BitmapDescriptorFactory.fromBitmap(bitmap)
}

internal fun cluster(
    context: Context,
    text: String,
    @ColorInt ovalBackground: Int
): BitmapDescriptor {
    val vectorDrawable: Drawable =
        ContextCompat.getDrawable(context, R.drawable.ic_map_marker_cluster)!!
    vectorDrawable.setBounds(
        0,
        0,
        vectorDrawable.intrinsicWidth,
        vectorDrawable.intrinsicHeight
    )
    val bitmap = Bitmap.createBitmap(
        vectorDrawable.intrinsicWidth,
        vectorDrawable.intrinsicHeight,
        Bitmap.Config.ARGB_8888
    )

    val canvas = Canvas(bitmap)
    val paint = Paint().apply {
        color = ovalBackground
        style = Paint.Style.FILL
    }

    val textPaint = TextPaint().apply {
        color = Color.WHITE
        textAlign = Paint.Align.CENTER
//                textSize = ScreenUtils.dpToPx(14).toFloat()
        typeface = Typeface.MONOSPACE
    }

    val textHeight = textPaint.descent() - textPaint.ascent()
    val textOffset = (textHeight / 2) - textPaint.descent()
    val bounds = RectF(
        0f,
        0f,
        vectorDrawable.intrinsicWidth.toFloat(),
        vectorDrawable.intrinsicHeight.toFloat()
    )
//            vectorDrawable.draw(canvas)
    canvas.drawOval(bounds, paint)
    canvas.drawText(text, bounds.centerX(), bounds.centerY() + textOffset, textPaint)

    return BitmapDescriptorFactory.fromBitmap(bitmap)
}