package egovframework.controller;

import egovframework.util.CommonPath;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
public class FileController {

    @GetMapping(path = "/upload/{fileName}.do")
    @ResponseBody
    public ResponseEntity<Resource> resourcePath(@PathVariable String fileName) {
        String imagePath = CommonPath.getImageUploadPath()  + "/" + fileName;
        FileSystemResource imageFile = new FileSystemResource(imagePath);
        try {
            if (imageFile.exists()) {
                HttpHeaders header = new HttpHeaders();
                Path filePath = Paths.get(imagePath);
                header.add("Content-Type", Files.probeContentType(filePath));
                return new ResponseEntity<Resource>(imageFile, header, HttpStatus.OK);
            }
            log.error("Not Found Image File : {}", fileName);
            return null;
        } catch (IOException e) {
            log.error("{}", e.getStackTrace());
            return null;
        }
    }
}

