package com.cn.fdapfe.common.utils.file;

import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileToMultipartFile implements MultipartFile {

    private final File file;
    private final String name;
    private final String originalFilename;
    private final String contentType;

    public FileToMultipartFile(File file, String name, String originalFilename, String contentType) {
        this.file = file;
        this.name = name;
        this.originalFilename = originalFilename;
        this.contentType = contentType;
    }

    public FileToMultipartFile(String filePath, String name) throws IOException {
        String contentType1;
        this.file = new File(filePath);
        this.name = name;
        this.originalFilename = file.getName();

        // 尝试确定内容类型
        Path path = Paths.get(filePath);
        contentType1 = Files.probeContentType(path);
        if (contentType1 == null) {
            contentType1 = "application/octet-stream";
        }
        this.contentType = contentType1;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return originalFilename;
    }

    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return file == null || file.length() == 0;
    }

    @Override
    public long getSize() {
        return file.length();
    }

    @Override
    public byte[] getBytes() throws IOException {
        try (InputStream is = new FileInputStream(file)) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = is.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            return buffer.toByteArray();
        }
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new FileInputStream(file);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        Files.copy(file.toPath(), dest.toPath());
    }
}