package cn.reghao.oss.store.config.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * 实现 PUT 请求上传文件
 * @author reghao
 * @date 2022-12-28 10:03:22
 */
@Slf4j
public class PutMessageConverter extends AbstractHttpMessageConverter<File> {
    public PutMessageConverter() {
        super(MediaType.ALL);
    }

    @Override
    protected boolean supports(Class<?> clazz) {
        return File.class.isAssignableFrom(clazz);
    }

    @Override
    protected File readInternal(Class<? extends File> clazz, HttpInputMessage inputMessage)
            throws IOException, HttpMessageNotReadableException {
        log.info("PUT 请求上传文件");
        InputStream inputStream = inputMessage.getBody();
        return saveStream(inputStream);
    }

    private File saveStream(InputStream inputStream) throws IOException {
        String tmpPath = String.format("/opt/tmp/tomcat/%s.dat", UUID.randomUUID());
        Files.copy(inputStream, Path.of(tmpPath), StandardCopyOption.REPLACE_EXISTING);
        File tmpFile = new File(tmpPath);
        /*tmpFile.createNewFile();
        FileOutputStream outputStream = new FileOutputStream(tmpFile);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.flush();
        outputStream.close();*/
        return tmpFile;
    }

    protected void writeInternal(File file, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        log.info("writeInternal");
    }
}
