package cn.reghao.oss.console.account.controller;

import cn.reghao.oss.console.account.service.FileService;
import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.jutil.web.ServletUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author reghao
 * @date 2024-01-20 17:24:58
 */
@Controller
@RequestMapping
public class FileController {
    private final FileService fileService;

    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @PostMapping(value = "/api/file/upload", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public String imageUpload(MultipartFile file) throws Exception {
        String url = fileService.putFile(file);
        Map<String, String> map = new HashMap<>();
        map.put("name", file.getOriginalFilename());
        map.put("url", url);
        return WebResult.success(map);
    }

    @GetMapping("/file/**")
    @ResponseBody
    public void getFile() throws IOException {
        HttpServletRequest servletRequest = ServletUtil.getRequest();
        String uri = servletRequest.getRequestURI();
        String uri1 = URLDecoder.decode(uri, StandardCharsets.UTF_8);
        String objectName =  uri1.replaceFirst("/", "");
        fileService.getFile(objectName);
    }
}
