package cc.smtweb.system.bpm.util;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class MemMultipartFile implements MultipartFile {
    private static final String DATA_IMAGE = "data:image/";
    private byte[] data;
    private String contentType;
    private String filename;

    public static MemMultipartFile build(String dataUrl) {
        if (dataUrl != null && dataUrl.startsWith(DATA_IMAGE)) {
            // data:image/png;base64,
            int pos1 = dataUrl.indexOf(';', DATA_IMAGE.length());
            int pos2 = dataUrl.indexOf(',', DATA_IMAGE.length());
            if (pos1 > 0 && pos2 > pos1) {
                byte[] data = Base64.decodeBase64(dataUrl.substring(pos2));

                if (data != null) {
                    String contentType = dataUrl.substring(5, pos1);
                    return new MemMultipartFile(contentType.replace('/', '.'), contentType, data);
                }
            }
        }

        return null;
    }

    private MemMultipartFile(String filename, String contentType, byte[] data) {
        this.data = data;
        this.contentType = contentType;
        this.filename = filename;
    }

    @Override
    public String getName() {
        return "data";
    }

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

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

    @Override
    public boolean isEmpty() {
        return data.length == 0;
    }

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

    @Override
    public byte[] getBytes() throws IOException {
        return data;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(data);
    }

    @Override
    public void transferTo(File file) throws IOException, IllegalStateException {
        try (FileOutputStream os = new FileOutputStream(file)) {
            os.write(data);
        }
    }
}
