package com.yeejoin.equipmanage.common.entity;

import com.yeejoin.equipmanage.common.exception.BaseException;
import lombok.NonNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class MyByteArrayMultipartFile implements MultipartFile {

	private String name;

	private String originalFilename;

	private String contentType;

	public MyByteArrayMultipartFile(String name, String originalFilename, String contentType, @NonNull byte[] bytes) {
		super();
		this.name = name;
		this.originalFilename = originalFilename;
		this.contentType = contentType;
		this.bytes = bytes;
	}

	public MyByteArrayMultipartFile() {
		super();
		// TODO Auto-generated constructor stub
	}

	public String getName() {
		return name;
	}

	public String getOriginalFilename() {
		return originalFilename;
	}

	public String getContentType() {
		return contentType;
	}

	public byte[] getBytes() {
		return bytes;
	}

	@NonNull
	byte[] bytes;

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

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

	@Override
	public InputStream getInputStream() {
		return new ByteArrayInputStream(bytes);
	}

	@Override
	public void transferTo(File destination) throws IOException {
		OutputStream outputStream = null;
		try {
			outputStream = new FileOutputStream(destination);
			outputStream.write(bytes);
		}catch(Exception e){
			throw new BaseException("系统异常！");
		}finally {
			if (outputStream != null) {
				outputStream.close();
			}
		}
	}
}
