package com.ffii.fpsms.modules.master.service

import com.ffii.core.utils.PdfUtils
import com.ffii.core.utils.QrCodeUtil
import com.ffii.fpsms.modules.master.entity.EquipmentDetailRepository
import com.ffii.fpsms.modules.master.web.ExportEquipmentQrCodeRequest
import com.ffii.fpsms.modules.master.web.PrintEquipmentQrCodeRequest
import com.ffii.fpsms.modules.master.print.A4PrintDriverRegistry
import net.sf.jasperreports.engine.JasperCompileManager
import net.sf.jasperreports.engine.JasperExportManager
import net.sf.jasperreports.engine.JasperReport
import net.sf.jasperreports.engine.JasperPrint
import org.springframework.core.io.ClassPathResource
import org.springframework.stereotype.Service
import java.io.FileNotFoundException
import java.io.File
import java.awt.GraphicsEnvironment
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString

@Service
class EquipmentQrCodeService(
    private val equipmentDetailRepository: EquipmentDetailRepository,
    private val printerService: PrinterService,
) {
    private val qrCodeHandleJrxmlPath = "qrCodeHandle/equipment_QrHandle.jrxml"

    /**
     * Compile the Jasper template once; compiling per request is expensive.
     */
    private val qrCodeHandleReport: JasperReport by lazy {
        val resource = ClassPathResource(qrCodeHandleJrxmlPath)
        if (!resource.exists()) {
            throw FileNotFoundException("Report file not found: $qrCodeHandleJrxmlPath")
        }
        resource.inputStream.use { JasperCompileManager.compileReport(it) }
    }

    /**
     * Cache the chosen Chinese font family name (font scanning is expensive).
     */
    private val chineseFontFamily: String by lazy {
        val availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().availableFontFamilyNames
        availableFonts.find { family ->
            family.contains("SimSun", ignoreCase = true) ||
                family.contains("Microsoft YaHei", ignoreCase = true) ||
                family.contains("STSong", ignoreCase = true) ||
                family.contains("SimHei", ignoreCase = true)
        } ?: "Arial Unicode MS"
    }

    fun exportEquipmentQrCode(request: ExportEquipmentQrCodeRequest): Map<String, Any> {
        val equipmentDetails = equipmentDetailRepository.findAllById(request.equipmentDetailIds)
        if (equipmentDetails.isEmpty()) {
            throw IllegalArgumentException("No equipment details found for the provided equipment detail IDs: ${request.equipmentDetailIds}")
        }
        
        val fields = mutableListOf<MutableMap<String, Any>>()
        
        for (equipmentDetail in equipmentDetails) {
            val field = mutableMapOf<String, Any>()
            
            val code = equipmentDetail.code ?: ""
            val equipmentCodeFromDetail = equipmentDetail.equipmentCode ?: ""
            
            if (code.isBlank() && equipmentCodeFromDetail.isBlank()) {
                continue
            }
            
            val qrContentMap = mapOf("equipmentCode" to equipmentCodeFromDetail)
            val qrCodeContent = Json.encodeToString(qrContentMap)
            
            val qrCodeImage = QrCodeUtil.generateQRCodeImage(qrCodeContent)
            
            field["username"] = code
            field["staffNo"] = code
            field["qrCode"] = qrCodeImage
            field["code"] = code
            
            fields.add(field)
        }
        
        if (fields.isEmpty()) {
            throw IllegalArgumentException("No valid equipment details found for the provided equipment detail IDs: ${request.equipmentDetailIds}")
        }
        
        val params: MutableMap<String, Any> = mutableMapOf()

        params["net.sf.jasperreports.default.pdf.encoding"] = "Identity-H"
        params["net.sf.jasperreports.default.pdf.embedded"] = true
        params["net.sf.jasperreports.default.pdf.font.name"] = chineseFontFamily
        
        val firstEquipmentDetail = equipmentDetails.firstOrNull()
        
        return mapOf(
            "report" to PdfUtils.fillReport(qrCodeHandleReport, fields, params),
            "fileName" to (firstEquipmentDetail?.code ?: "equipment_qrcode")
        )
    }

    fun printEquipmentQrCode(request: PrintEquipmentQrCodeRequest) {
        val printer = printerService.findById(request.printerId) ?: throw NoSuchElementException("No such printer")
        val pdf = exportEquipmentQrCode(ExportEquipmentQrCodeRequest(request.equipmentDetailIds))
        val jasperPrint = pdf["report"] as JasperPrint
        val tempPdfFile = File.createTempFile("print_job_", ".pdf")

        try {
            JasperExportManager.exportReportToPdfFile(jasperPrint, tempPdfFile.absolutePath)
            val printQty = if (request.printQty == null || request.printQty <= 0) 1 else request.printQty
            printer.ip?.let { ip ->
                val port = printer.port ?: 9100
                val driver = A4PrintDriverRegistry.getDriver(printer.brand)
                driver.print(tempPdfFile, ip, port, printQty)
            }
        } finally {
            tempPdfFile.delete()
        }
    }
}
