package me.zhengjie.modules.system.domain.dto;

import me.zhengjie.utils.FileUtil;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImageDataVo {

    private List<ByteArrayOutputStream> imgByteArray;

    public ImageDataVo() {
        this.imgByteArray = new ArrayList<>();
    }

    public String saveImage(byte[] imageData, String imgDir) {
        MultipartFile multipartFile = new MockMultipartFile("file", "img.jpg", "application/octet-stream", imageData);
        File file = FileUtil.upload(multipartFile, imgDir);
        return file.getName();
    }

    public void imgWrite(byte[] data) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            baos.write(data);
            imgByteArray.add(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public byte[] getFullImageData() {
        ByteArrayOutputStream fullData = new ByteArrayOutputStream();
        try {
            for (ByteArrayOutputStream chunk : imgByteArray) {
                fullData.write(chunk.toByteArray());
            }
            return fullData.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
