package com.isidroid.rendering.ext

import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.RectF
import androidx.annotation.ColorInt
import com.isidroid.rendering.constant.PrintSize
import com.isidroid.rendering.model.PrintCanvas


internal fun Canvas.drawBitmap(
    picture: Bitmap,
    dpix: Int,
    @PrintSize printSize: Int,
    scale: Float,
    canvasSize: PrintCanvas,
    paint: Paint,
    noMargins: Boolean,
    maxSize: Int
) {
    val image = createBitmapWithScaling(
        dpix = dpix,
        picture = picture,
        printSize = printSize,
        settingsScale = scale,
        canvasSize = canvasSize,
        maxSize = maxSize
    )

    val left = if (noMargins) 0f else canvasSize.marginLeft
    val top = if (noMargins) 0f else canvasSize.marginTop

    drawBitmap(image, left, top, paint)
    image.recycle()
}


internal fun Canvas.drawBackground(width: Int, height: Int, color: Int = Color.WHITE) {
    drawRect(
        Rect(0, 0, width, height),
        Paint().apply {
            this.color = color
            this.style = Paint.Style.FILL
        }
    )
}

internal fun Canvas.drawBorders(canvasSize: PrintCanvas) {
    val paint = Paint().apply {
        color = Color.BLACK
        alpha = 50
        style = Paint.Style.FILL
    }

    val borders = calculateBorders(canvasSize)

    borders.forEach { drawRect(it, paint) }
}


internal fun createPaint(
    greyscale: Boolean = false,
    alpha: Int? = null,
    style: Paint.Style? = null,
    @ColorInt color: Int? = null
): Paint {
    val paint = Paint()
        .apply {
            alpha?.also { this.alpha = it }
            style?.also { this.style = it }
            color?.also { this.color = it }
        }

    if (greyscale) {
        val cm = ColorMatrix().apply { setSaturation(0f) }
        val colorMatrixFilter = ColorMatrixColorFilter(cm)
        paint.colorFilter = colorMatrixFilter
    }

    return paint
}

internal fun calculateBorders(canvasSize: PrintCanvas): List<RectF> {
    return with(canvasSize) {
        val left = RectF(0f, 0f, marginLeft, height)
        val right = RectF(marginLeft + printWidth, 0f, width, height)

        val top = RectF(marginLeft, 0f, marginLeft + printWidth, marginTop)
        val bottom = RectF(marginLeft, marginTop + printHeight, marginLeft + printWidth, height)

        listOf(
            left,
            right,
            top,
            bottom
        )
    }
}