package com.bonus.obs.controller;

import com.bonus.common.core.domain.R;
import com.bonus.common.core.utils.file.FileUtils;
import com.bonus.obs.service.ObsService;
import com.obs.services.model.DeleteObjectResult;
import com.obs.services.model.ObsObject;
import com.obs.services.model.PutObjectResult;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/obs")
public class ObsController {
    @Resource
    private ObsService service;

    /**
     * 文件上传
     *
     * @param param 文件流
     * @return 文件信息
     */
    @PostMapping("/upload")
    public R<PutObjectResult> uploadFile(MultipartFile param) {
        return service.uploadFile(param);
    }

    /**
     * 删除文件从OBS
     *
     * @param objectKey 文件在OBS中的键
     */
    @PostMapping("/delete")
    public R<DeleteObjectResult> deleteFile(String objectKey) {
        return service.deleteFile(objectKey);
    }


    /**
     * 文件下载
     *
     * @param objectKey obs文件存储地址
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response, @RequestParam String objectKey) {
        R<ObsObject> obsObjectR = service.downloadFile(objectKey);
        try {
            if (R.isError(obsObjectR)) {
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return;
            }
            if (obsObjectR.getData() == null) {
                response.setStatus(HttpStatus.NOT_FOUND.value());
                return;
            }
            InputStream inputStream = obsObjectR.getData().getObjectContent();
            String safeFileName = FileUtils.getFileNameFromPath(objectKey);
            String encodedFileName = URLEncoder.encode(safeFileName, StandardCharsets.UTF_8.toString());
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
            try (OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            } catch (IOException e) {
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        } catch (IllegalArgumentException e) {
            response.setStatus(HttpStatus.BAD_REQUEST.value());
        } catch (Exception e) {
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
    }

}
