package com.example.ops_android.printer

class PrintJob(private val manager: PrinterManager) {

    private var textContent: String? = null
    private var qrContent: String? = null
    private var barcodeContent: String? = null
    private var lineFeeds: Int = 0
    private var useLabelMode: Boolean = false

    fun text(text: String): PrintJob {
        textContent = text
        return this
    }

    fun qr(content: String): PrintJob {
        qrContent = content
        return this
    }

    fun barcode(content: String): PrintJob {
        barcodeContent = content
        return this
    }

    fun lineFeed(count: Int = 1): PrintJob {
        lineFeeds = count
        return this
    }

    fun labelMode(): PrintJob {
        useLabelMode = true
        return this
    }

    /** 初始化 → 添加内容 → 提交 → 等待 → 关闭 */
    fun build(): Result<Unit> = runCatching {
        manager.initDevice().getOrThrow()

        if (useLabelMode)
            manager.enableMarkDetection(true).getOrThrow()

        textContent?.let { manager.addText(it).getOrThrow() }
        qrContent?.let { manager.addQR(it).getOrThrow() }
        barcodeContent?.let { manager.addBarcode(it).getOrThrow() }
        if (lineFeeds > 0) manager.addLineFeed(lineFeeds).getOrThrow()

        manager.commit().getOrThrow()
    }

    /** 初始化 → 添加内容 → 提交（不关闭） */
    fun print(): Result<Unit> = runCatching {
        manager.ensureOpen().getOrThrow()

        if (useLabelMode)
            manager.enableMarkDetection(true).getOrThrow()

        textContent?.let { manager.addText(it).getOrThrow() }
        qrContent?.let { manager.addQR(it).getOrThrow() }
        barcodeContent?.let { manager.addBarcode(it).getOrThrow() }
        if (lineFeeds > 0) manager.addLineFeed(lineFeeds).getOrThrow()

        manager.commit().getOrThrow()
    }
}
