package com.isidroid.rendering.ext

import android.graphics.Bitmap
import android.graphics.Canvas
import com.isidroid.rendering.constant.PrintOrientation
import com.isidroid.rendering.constant.PrintSize
import com.isidroid.rendering.model.PrintCanvas
import com.isidroid.rendering.model.RenderSettingsV2

internal fun createRenderBitmap(
    settings: RenderSettingsV2,
    printCanvas: PrintCanvas,
    dpix: Int,
    picture: Bitmap,
    maxSize: Int,
    bitmapConfig: Bitmap.Config
): Bitmap {
    val noMargins = settings.printSize in arrayOf(PrintSize.FIT_TO_PAPER, PrintSize.FILL_PAGE)
    val hasBorders =
        settings.showPrintableArea //settings.printSize in arrayOf(PrintSize.FIT_TO_PAPER, PrintSize.FILL_PAGE, PrintSize.PAPER_ORIGINAL_PAGE)

    val scaledCanvasSize = getScaledPrintCanvas(
        filePath = settings.filePath,
        orientation = settings.orientation,
        scale = settings.scale,
        printCanvas = printCanvas,
    )

    val scaleFactor = if (settings.canvasWidth > 0) settings.canvasWidth / scaledCanvasSize.width else 1f
    val scaledCanvas2 = scaledCanvasSize.copy(
        width = scaleFactor * scaledCanvasSize.width,
        height = scaleFactor * scaledCanvasSize.height,
        printWidth = scaleFactor * scaledCanvasSize.printWidth,
        printHeight = scaleFactor * scaledCanvasSize.printHeight,
        marginLeft = scaleFactor * scaledCanvasSize.marginLeft,
        marginTop = scaleFactor * scaledCanvasSize.marginTop,
        marginRight = scaleFactor * scaledCanvasSize.marginRight,
        marginBottom = scaleFactor * scaledCanvasSize.marginBottom,

        )

    val bitmap = Bitmap.createBitmap(
        scaledCanvas2.width.toInt(),
        scaledCanvas2.height.toInt(),
        bitmapConfig
    )

    val canvas = Canvas(bitmap)
    val paint = createPaint(settings.greyscale)

    // draw a white background
    canvas.drawBackground(
        width = scaledCanvasSize.width.toInt(),
        height = scaledCanvasSize.height.toInt(),
    )

    canvas.drawBitmap(
        dpix = dpix,
        picture = picture,
        printSize = settings.printSize,
        scale = scaleFactor,
        canvasSize = scaledCanvas2,
        paint = paint,
        noMargins = noMargins,
        maxSize = maxSize
    )

    if (hasBorders && !settings.isRealSize)
        canvas.drawBorders(scaledCanvas2)

    return bitmap
}

internal fun calculateScaleFactor(cWidth: Float, cHeight: Float, width: Float, height: Float): Float? {
    val factor = cWidth / width
    val check = height * factor

    return if (check <= cHeight) factor else null
}

internal fun getScaledPrintCanvas(filePath: String, @PrintOrientation orientation: Int, printCanvas: PrintCanvas, scale: Float): PrintCanvas {
    val isPortrait = isPicturePortrait(filePath, orientation)
    val sizes = if (isPortrait) printCanvas else printCanvas.rotate()
    return scaledPrintCanvas(sizes, scale)
}
