package com.upsfj.sfjprojectbackend.controller;

import com.upsfj.sfjprojectbackend.mapper.AlgorithmMapper;
import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("/api/file")
public class FileController {
    @Resource
    MinioClient client;

    @Resource
    AlgorithmMapper algorithmMapper;

    @PostMapping("/upload")
    public String upload(@RequestParam("file")MultipartFile file,@RequestParam("algorithm_id") Integer algorithm_id) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        System.out.println(file);
        System.out.println(algorithm_id);
        InputStream stream = file.getInputStream();
        String name = UUID.randomUUID().toString()+".jpg";
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket("algorithm")
                .object(name)
                .stream(stream, file.getSize(), -1)
                .contentType("image/jpeg")
                .build();

        client.putObject(args);
//        name = +name;
        if (algorithm_id != 999){
            algorithmMapper.updateAlgorithmImg("http://localhost:9000/algorithm/"+name,algorithm_id);
        }

        return  name;
    }

    @GetMapping("/getimg/{name}")
    public void file(@PathVariable("name") String name, HttpServletResponse response) throws Exception{
        GetObjectResponse object = client.getObject(GetObjectArgs.builder().bucket("algorithm").object(name).build());
        ServletOutputStream stream = response.getOutputStream();
//        response.setContentType(object.contentType());
        stream.write(object.readAllBytes());

    }
}
