package com.ffii.fpsms.modules.master.web

import com.ffii.fpsms.modules.master.entity.Warehouse
import com.ffii.fpsms.modules.master.entity.projections.WarehouseCombo
import com.ffii.fpsms.modules.master.service.WarehouseService
import com.ffii.fpsms.modules.master.service.WarehouseQrCodeService
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.ServletRequestBindingException
import com.ffii.fpsms.modules.master.web.models.SaveWarehouseRequest
import jakarta.validation.Valid
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
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 org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.multipart.MultipartHttpServletRequest
import net.sf.jasperreports.engine.JasperExportManager
import net.sf.jasperreports.engine.JasperPrint
import java.io.OutputStream
import com.ffii.fpsms.modules.master.web.models.StockTakeSectionInfo
import com.ffii.fpsms.modules.master.web.models.UpdateSectionDescriptionRequest
@RestController
@RequestMapping("/warehouse")
class WarehouseController(
    private val warehouseService: WarehouseService,
    private val warehouseQrCodeService: WarehouseQrCodeService
) {
    @GetMapping
    fun getWarehouses(): List<Warehouse> {
        return warehouseService.getWarehouses()
    }

    @GetMapping("/combo")
    fun findCombo(): List<WarehouseCombo> {
        return warehouseService.findCombo()
    }

    @DeleteMapping("/{id}")
    fun deleteWarehouse(@PathVariable id: Long): List<Warehouse> {
        return warehouseService.markDeleted(id)
    }

    @PostMapping("/save")
    fun saveWarehouse(@Valid @RequestBody request: SaveWarehouseRequest): Warehouse {
        return warehouseService.saveWarehouse(request)
    }

    @PostMapping("/import")
    @Throws(ServletRequestBindingException::class)
    fun importExcel(request: HttpServletRequest): ResponseEntity<*> {
        var workbook: Workbook? = null;

        try {
            val multipartFile = (request as MultipartHttpServletRequest).getFile("multipartFileList")
            workbook = XSSFWorkbook(multipartFile?.inputStream)
        } catch (e: Exception) {
            println(e)
        }

        return ResponseEntity.ok(warehouseService.importExcel(workbook))
    }
    @PostMapping("/importNew")
    @Throws(ServletRequestBindingException::class)
    fun importNewExcel(request: HttpServletRequest): ResponseEntity<*> {
        var workbook: Workbook? = null;

        try {
            val multipartFile = (request as MultipartHttpServletRequest).getFile("multipartFileList")
            workbook = XSSFWorkbook(multipartFile?.inputStream)
        } catch (e: Exception) {
            println(e)
        }

        return ResponseEntity.ok(warehouseService.importNewExcel(workbook))
    }

    @PostMapping("/export-qrcode")
    @CrossOrigin(origins = ["*"], allowedHeaders = ["*"])
    fun exportQrCode(@Valid @RequestBody request: ExportWarehouseQrCodeRequest, response: HttpServletResponse) {
        response.setHeader("Access-Control-Allow-Origin", "*")
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        response.setHeader("Access-Control-Allow-Headers", "*")
        response.characterEncoding = "utf-8"
        response.contentType = "application/pdf"
        val out: OutputStream = response.outputStream
        val pdf = warehouseQrCodeService.exportWarehouseQrCode(request)
        val jasperPrint = pdf["report"] as JasperPrint
        val fileName = pdf["fileName"] as String
        response.addHeader("Content-Disposition", "attachment; filename=\"${fileName}_qrcode.pdf\"")
        out.write(JasperExportManager.exportReportToPdf(jasperPrint))
        out.flush()
    }
    @PostMapping("/print-qrcode")
    fun printQrCode(@Valid @RequestBody request: PrintWarehouseQrCodeRequest) {
        warehouseQrCodeService.printWarehouseQrCode(request)
    }
    @GetMapping("/stockTakeSections")
fun getStockTakeSections(): List<StockTakeSectionInfo> {
    return warehouseService.getStockTakeSections()
}

// PATCH /warehouse/section/{section}/description  (body: { "stockTakeSectionDescription": "demo1" })
@org.springframework.web.bind.annotation.PatchMapping("/section/{section}/description")
fun updateSectionDescription(
    @PathVariable section: String,
    @RequestBody body: UpdateSectionDescriptionRequest
): Unit {
    warehouseService.updateSectionDescription(section, body.stockTakeSectionDescription)
}

// POST /warehouse/{id}/clearSection
@PostMapping("/{id}/clearSection")
fun clearWarehouseSection(@PathVariable id: Long): Warehouse {
    warehouseService.clearWarehouseSection(id)
    return warehouseService.findById(id)!!
}
}