package com.wmyun.module.infra.controller.admin.file;

import com.wmyun.module.infra.controller.admin.file.vo.preview.CheckFileInfoVo;
import com.wmyun.module.infra.service.file.FilePreviewService;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.security.PermitAll;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.Enumeration;

import static com.wmyun.module.infra.framework.file.core.utils.FileTypeUtils.writeAttachment;

/**
 * @Description: 文件预览Wopi
 * @Date: 2025/2/26 18:18
 * @Created: by ZZSLL
 */

@Tag(name = "管理后台 - 文件预览")
@RestController
@RequestMapping("/infra/file/preview/wopi")
@Slf4j
public class OfficePreviewController {

    @Autowired
    private FilePreviewService previewService;

    @GetMapping("/files/{fileId}")
    @PermitAll
    public ResponseEntity<CheckFileInfoVo> getFileInfo(@PathVariable("fileId") String fileId) {
        return ResponseEntity.ok().body(previewService.createPreviewInfo(fileId));
    }

    @GetMapping(value = "/files/{fileId}/contents")
    @PermitAll
    public void getFileContents(@PathVariable String fileId, HttpServletResponse response) {
        previewService.getFileContent(fileId, response);
    }

    @RequestMapping(value = "/files/{fileId}/contents", method = {RequestMethod.POST, RequestMethod.PUT})
    @PermitAll
    public ResponseEntity<?> putFileContents(@PathVariable String fileId, InputStream contentStream, HttpServletRequest request) {
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String name	= enumeration.nextElement();
            String value = request.getHeader(name);
            log.info("{} = {}", name, value);
        }
        Long size = Long.valueOf(request.getHeader("content-length"));
        previewService.saveFile(fileId, contentStream, size);
        return ResponseEntity.ok().build();
    }
}
