package com.njcn.advance.utils;

import cn.hutool.core.codec.Base64;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class InstantiateUtil<E> {
    private static final Logger logger= LoggerFactory.getLogger(InstantiateUtil.class);


    public byte[] instantiate(E e) {
        if (e == null) {
            return null;
        }

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(e);
            objectOutputStream.close();
            return byteArrayOutputStream.toByteArray();

        } catch (IOException e1) {
            logger.error("发生异常，"+e1.getMessage());
        }

        return null;
    }

    public <E> E deInstantiate(byte[] bytes) {
        if (bytes == null) {
            return null;
        }

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            try {
                return (E) objectInputStream.readObject();
            } catch (ClassNotFoundException e) {
                logger.error("发生异常，"+e.getMessage());
            }
        } catch (IOException e) {
            logger.error("发生异常，"+e.getMessage());
        }

        return null;
    }

    public String stringInstantiate(E e) { //序列化对象的byte[]数组转为字符串(包装类可不调用)
        byte[] bytes = instantiate(e);

        if (bytes != null && bytes.length>0 ) {
            return Base64.encode(bytes);
        }

        return "";
    }

    public byte[] stringDeInstantiate(String str) { //stringInstantiate方法还原为byte[]数组
        if (!StringUtils.isEmpty(str)) {
            return Base64.decode(str);
        }
        return null;
    }
}
