package com.ffii.fpsms.modules.jobOrder.web

import com.ffii.fpsms.modules.jobOrder.service.PlasticBagPrinterService
import com.ffii.fpsms.modules.jobOrder.web.model.PrintRequest
import com.ffii.fpsms.modules.jobOrder.web.model.LaserRequest
import com.ffii.fpsms.modules.jobOrder.web.model.Laser2Request
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpHeaders
import org.springframework.web.bind.annotation.*
import java.time.LocalDate
import org.springframework.http.ResponseEntity

@RestController
@RequestMapping("/plastic")
class PlasticBagPrinterController(
    private val plasticBagPrinterService: PlasticBagPrinterService,
) {

    /**
     * Test API to generate and download the printer job files as a ZIP.
     * ONPACK2030
     */
    @GetMapping("/get-printer6")
    fun testPrintJob(
        @RequestParam itemCode: String,
        @RequestParam lotNo: String,
        @RequestParam expiryDate: String,
        @RequestParam productName: String,
        response: HttpServletResponse
    ) {
        // Generate the ZIP bundle via the service
        val zipBytes = plasticBagPrinterService.generatePrintJobBundle(
            itemCode, 
            lotNo, 
            expiryDate, 
            productName
        )

        // Set headers for file download
        response.contentType = "application/zip"
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"TT_${itemCode}_Job.zip\"")
        response.setContentLength(zipBytes.size)

        // Write to response stream
        response.outputStream.write(zipBytes)
        response.outputStream.flush()
    }

    @PostMapping("/print-dataflex")
    fun printDataFlex(@RequestBody request: PrintRequest): ResponseEntity<String> {
        return try {
            plasticBagPrinterService.sendDataFlexJob(request)
            ResponseEntity.ok("Print command sent successfully")
        } catch (e: Exception) {
            ResponseEntity.status(500).body("Error: ${e.message}")
        }
    }

    @PostMapping("/print-laser")
    fun printLaser(@RequestBody request: LaserRequest): ResponseEntity<String> {
        return try {
            // Call the laser marking service
            plasticBagPrinterService.sendLaserMark(request)
            ResponseEntity.ok("Laser marking command sent successfully to ${request.printerIp}")
        } catch (e: Exception) {
            // Log the error and return 500 status
            ResponseEntity.status(500).body("Laser Error: ${e.message}")
        }
    }

    @PostMapping("/preview-laser")
    fun previewLaser(@RequestBody request: LaserRequest): ResponseEntity<String> {
        return try {
            plasticBagPrinterService.sendLaserPreview(request)
            ResponseEntity.ok("Red light activated")
        } catch (e: Exception) {
            ResponseEntity.status(500).body("Preview Error: ${e.message}")
        }
    }

    @PostMapping("/print-tsc")
    fun printTsc(@RequestBody request: PrintRequest): ResponseEntity<String> {
        return try {
            plasticBagPrinterService.sendTscPrintJob(request)
            ResponseEntity.ok("TSC Print command sent to ${request.printerIp}")
        } catch (e: Exception) {
            ResponseEntity.status(500).body("Error: ${e.message}")
        }
    }

    @GetMapping("/test-x40")
    fun testX40(
        @RequestParam printerIp: String,
        @RequestParam(defaultValue = "3001") port: Int
    ): ResponseEntity<String> {
        val (success, message) = plasticBagPrinterService.testSmartDateX40Tcp(printerIp, port)
        return if (success) {
            ResponseEntity.ok("OK - $message")
        } else {
            ResponseEntity.status(503).body("FAIL - $message")
        }
    }

    @PostMapping("/print-laser-tcp")
    fun printLaserTcp(@RequestBody request: Laser2Request): ResponseEntity<String> {
        return try {
            val success = plasticBagPrinterService.sendLaserTcpUpdateAndMark(
                ip = request.printerIp,
                port = request.printerPort.toInt(),
                textChannel3 = request.textChannel3 
                    ?: throw IllegalArgumentException("缺少 textChannel3"),
                textChannel4 = request.textChannel4 
                    ?: throw IllegalArgumentException("缺少 textChannel4"),
                text3ObjectName = request.text3ObjectName ?: "Text3",
                text4ObjectName = request.text4ObjectName ?: "Text4"
            )

            if (success) {
                ResponseEntity.ok("Han's Laser TCP: 更新文字並觸發打標成功")
            } else {
                ResponseEntity.status(500)
                    .body("Han's Laser TCP: 部分或全部命令失敗，請檢查連接、物件名稱或 EZCAD TCP Server")
            }
        } catch (e: Exception) {
            ResponseEntity.status(500).body("Laser TCP Error: ${e.message}")
        }
    }

}