package com.bcxin.ins.third.tyx.pingan.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class Base64Utils {

	private static final int CACHE_SIZE = 1024;

	public static byte[] decode(String base64) throws IOException {
		return (new BASE64Decoder()).decodeBuffer(base64);
	}

	public static String encode(byte[] bytes) {
		return new String((new BASE64Encoder()).encode(bytes));
	}

	public static String encodeFile(String filePath) throws IOException {
		byte[] bytes = fileToByte(filePath);
		return encode(bytes);
	}

	public static void decodeToFile(String filePath, String base64)
			throws IOException {
		byte[] bytes = decode(base64);
		byteArrayToFile(bytes, filePath);
	}

	public static byte[] fileToByte(String filePath) throws IOException {
		byte[] data = new byte[0];
		File file = new File(filePath);
		if (file.exists()) {
			try(FileInputStream in = new FileInputStream(file);
				ByteArrayOutputStream out = new ByteArrayOutputStream(2048);){
				byte[] cache = new byte[CACHE_SIZE];
				int nRead = 0;
				while ((nRead = in.read(cache)) != -1) {
					out.write(cache, 0, nRead);
					out.flush();
				}
				data = out.toByteArray();
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return data;
	}

	public static void byteArrayToFile(byte[] bytes, String filePath)
			throws IOException {
		File destFile = new File(filePath);
		if (!destFile.getParentFile().exists()) {
			destFile.getParentFile().mkdirs();
		}
		destFile.createNewFile();
		try(InputStream in = new ByteArrayInputStream(bytes);
			OutputStream out = new FileOutputStream(destFile);) {
			byte[] cache = new byte[CACHE_SIZE];
			int nRead = 0;
			while ((nRead = in.read(cache)) != -1) {
				out.write(cache, 0, nRead);
				out.flush();
			}
		}
	}

}