package com.njzscloud.common.minio.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.njzscloud.common.core.tuple.Tuple2;
import com.njzscloud.common.core.utils.R;
import com.njzscloud.common.minio.util.AliOSS;
import com.njzscloud.common.minio.util.Minio;
import com.njzscloud.common.mvc.util.FileResponseUtil;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OSSController {

    @GetMapping("/end_mlt_upload")
    public R<?> endMltUpload(String objectName, String uploadId, int partNum) {
        Minio.endMltUpload(objectName, uploadId, partNum);
        return R.success();
    }

    @GetMapping("/start_mlt_upload")
    public R<Tuple2<String, List<String>>> startMltUpload(
            String objectName,
            String contentType,
            int partNum) {
        return R.success(Minio.startMltUpload(objectName, contentType, partNum));
    }

    @GetMapping("/obtain_presigned_url")
    public R<Map<String, String>> obtainPresignedUrl(@RequestParam(value = "filename") String filename) {
        String objectName = IdUtil.fastSimpleUUID();
        if (StrUtil.isNotBlank(filename)) {
            objectName = objectName + "." + FileUtil.extName(filename);
        }
        return R.success(AliOSS.obtainPresignedUrl(objectName));
    }

    @GetMapping("/download/{bucketName}/{objectName}")
    public void obtainFile(
            @PathVariable("bucketName") String bucketName,
            @PathVariable("objectName") String objectName,
            HttpServletResponse response) {
        Tuple2<InputStream, String> tuple2 = AliOSS.obtainFile(bucketName, objectName);
        FileResponseUtil.download(response, tuple2.get_0(), tuple2.get_1(), objectName);
    }
}
