package org.jeecg.modules.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.jeecg.common.exception.JeecgBootException;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

@Slf4j
public class Base64Util {

	private static final String ENCODING = "UTF-8";

	public static String encode(String input) {
		return encode(input,ENCODING);
	}

	public static String encode(String input,String charsetName) {
		try {
			input = new String (Base64.encodeBase64(input.getBytes(charsetName)),charsetName);
		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
			log.error(e.getMessage(), e);
			input = "";
		}
		return input;
	}

	public static String encode(byte[] input) {
		String ouput="";
		try {
			ouput = new String (Base64.encodeBase64(input),ENCODING);
		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
			log.error(e.getMessage(), e);
			ouput = "";
		}
		return ouput;
	}

	public static String decode(String input) {
		return decode(input,ENCODING);
	}

	public static String decode(String input,String charsetName) {
		String ouput = "";
		try {
			byte[] decodeBase64 = Base64.decodeBase64(input.getBytes(charsetName));
			ouput = new String(decodeBase64, charsetName);
		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		return ouput;
	}

	public static byte[] decodeArray(String input) {
		byte[] decodeBase64=new byte[0];
		try {
			decodeBase64 = Base64.decodeBase64(input.getBytes(ENCODING));
		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
			log.error(e.getMessage(), e);
		}
		return decodeBase64;
	}

	/**
	 * base64转化成 inputStream
	 *
	 * @param base64
	 * @return
	 */
	public static InputStream base64ToInputStream(String base64) {
		ByteArrayInputStream stream = null;
		try {
			byte[] bytes = java.util.Base64.getDecoder().decode(base64);
			stream = new ByteArrayInputStream(bytes);
		} catch (Exception e) {
			throw new JeecgBootException("base64转字符流失败");
		}
		return stream;
	}
}
