package com.ffii.fpsms.modules.stock.web

import com.ffii.fpsms.modules.master.web.models.MessageResponse
import com.ffii.fpsms.modules.stock.service.StockInLineService
import com.ffii.fpsms.modules.stock.web.model.ExportQrCodeRequest
import com.ffii.fpsms.modules.stock.web.model.SaveStockInLineRequest
import jakarta.servlet.http.HttpServletResponse
import jakarta.validation.Valid
import net.sf.jasperreports.engine.JasperExportManager
import net.sf.jasperreports.engine.JasperPrint
import org.springframework.context.NoSuchMessageException
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.OutputStream
import java.io.UnsupportedEncodingException
import java.text.ParseException


@RestController
@RequestMapping("/stockInLine")
class StockInLineController(
    private val stockInLineService: StockInLineService
) {
    @PostMapping("/create")
    fun create(@Valid @RequestBody newItem: SaveStockInLineRequest): MessageResponse {
        return stockInLineService.create(newItem)
    }

    @PostMapping("/update")
    fun update(@Valid @RequestBody newItem: SaveStockInLineRequest): MessageResponse {
        return stockInLineService.update(newItem)
    }

    @PostMapping("/print-label")
    @Throws(UnsupportedEncodingException::class, NoSuchMessageException::class, ParseException::class, Exception::class)
    fun printLabel(@Valid @RequestBody request: ExportQrCodeRequest, response: HttpServletResponse) {
        response.characterEncoding = "utf-8";
        response.contentType = "application/pdf";
        val out: OutputStream = response.outputStream
        val pdf: Map<String, Any> = stockInLineService.exportStockInLineQrcode(request)
        val jasperPrint = pdf["report"] as JasperPrint
        response.addHeader("filename", "${pdf["fileName"]}.pdf")
        out.write(JasperExportManager.exportReportToPdf(jasperPrint));
    }


}