package ink.wgink.util;

import ink.wgink.exceptions.base.SystemException;
import ink.wgink.util.string.WStringUtil;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: ArrayListUtil
 * @Description: 列表工具
 * @Author: WangGeng
 * @Date: 2020/8/24 17:25
 * @Version: 1.0
 **/
public class ArrayListUtil {

    public static <T extends Serializable> List<T> deepClone(List<? extends Serializable> sourceList, Class<T> clazz) {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try {
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(sourceList);
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream inStream = new ObjectInputStream(byteIn);
            List<T> destList = (List<T>) inStream.readObject();
            return destList;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取bean中的字符串ID值列表
     *
     * @param beans
     * @param propertyName
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> List<String> listBeanStringIdValue(List<T> beans, String propertyName, Class<T> beanClass) {
        if (beans.isEmpty()) {
            return new ArrayList<>();
        }
        Set<String> beanStringIdSet = new HashSet<>();
        try {
            for (Object bean : beans) {
                Method method = bean.getClass().getMethod("get" + WStringUtil.firstToUpper(propertyName));
                Object result = method.invoke(bean);
                if (result == null) {
                    continue;
                }
                beanStringIdSet.add(result.toString());
            }
        } catch (Exception e) {
            throw new SystemException(e);
        }
        return new ArrayList<>(beanStringIdSet);
    }
}
