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

import com.ffii.fpsms.modules.stock.service.StockTakeService
import jakarta.servlet.http.HttpServletRequest
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.util.IOUtils
import org.apache.poi.xssf.streaming.SXSSFWorkbook
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.ServletRequestBindingException
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.multipart.MultipartHttpServletRequest

@RequestMapping("/stockTake")
@RestController
class StockTakeController(
    val stockTakeService: StockTakeService,
) {
    @PostMapping("/import")
    @Throws(ServletRequestBindingException::class)
    fun importExcel(request: HttpServletRequest): ResponseEntity<*> {
        var workbook: Workbook? = null;

        try {
            println("Start")
            val multipartFile = (request as MultipartHttpServletRequest).getFile("multipartFileList")
            workbook = XSSFWorkbook(multipartFile?.inputStream)

            // Use SXSSFWorkbook instead of XSSFWorkbook
//            IOUtils.setByteArrayMaxOverride(300_000_000)
//            workbook = SXSSFWorkbook(XSSFWorkbook(multipartFile?.inputStream))
            // Optional: Configure SXSSF to limit memory usage
//            workbook.setCompressTempFiles(true)
        } catch (e: Exception) {
            println("Excel Wrong")
            println(e)
        }

        return ResponseEntity.ok(stockTakeService.importExcel(workbook))
    }
    @PostMapping("/createForSections")
    fun createStockTakeForSections(): ResponseEntity<Map<String, String>> {
        val result = stockTakeService.createStockTakeForSections()
        return ResponseEntity.ok(result)
    }

}