package app.voltplan.cable.pdf

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import androidx.core.content.FileProvider
import java.io.File

/** A4 portrait at 72 dpi. */
const val PAGE_W = 595
const val PAGE_H = 842
const val MARGIN = 40f

/** Lightweight paginating canvas for the PDF exporters. */
class PdfWriter(private val doc: PdfDocument) {
    private var pageNumber = 0
    private var page: PdfDocument.Page? = null
    var y = MARGIN
        private set

    val canvas get() = page!!.canvas

    fun beginPage() {
        page?.let { doc.finishPage(it) }
        pageNumber++
        page = doc.startPage(PdfDocument.PageInfo.Builder(PAGE_W, PAGE_H, pageNumber).create())
        y = MARGIN
        footer()
    }

    fun ensure(space: Float) {
        if (page == null) beginPage()
        else if (y + space > PAGE_H - MARGIN - 20) beginPage()
    }

    fun text(s: String, size: Float, color: Int = Color.BLACK, bold: Boolean = false, x: Float = MARGIN) {
        ensure(size + 6)
        val p = Paint().apply {
            this.color = color
            textSize = size
            isAntiAlias = true
            if (bold) isFakeBoldText = true
        }
        y += size
        canvas.drawText(s, x, y, p)
        y += 4
    }

    fun gap(h: Float) { y += h }

    fun divider() {
        ensure(8f)
        val p = Paint().apply { color = Color.LTGRAY; strokeWidth = 1f }
        canvas.drawLine(MARGIN, y, PAGE_W - MARGIN, y, p)
        y += 8
    }

    private fun footer() {
        val p = Paint().apply { color = Color.GRAY; textSize = 9f; isAntiAlias = true }
        canvas.drawText("Cable by VoltPlan", PAGE_W - MARGIN - 120, PAGE_H - MARGIN + 10, p)
        canvas.drawText("$pageNumber", PAGE_W / 2f, PAGE_H - MARGIN + 10, p)
    }

    fun finish() { page?.let { doc.finishPage(it) } }
}

object PdfShare {
    fun writeToCache(context: Context, fileName: String, doc: PdfDocument): File {
        val dir = File(context.cacheDir, "exports").apply { mkdirs() }
        val file = File(dir, fileName)
        file.outputStream().use { doc.writeTo(it) }
        doc.close()
        return file
    }

    fun share(context: Context, file: File) {
        val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
        val intent = Intent(Intent.ACTION_SEND).apply {
            type = "application/pdf"
            putExtra(Intent.EXTRA_STREAM, uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        context.startActivity(Intent.createChooser(intent, null).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
    }
}
