package cn.freemud;

import org.junit.Test;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;


public class AllTests {

    @Test
    public void entityTest() throws Exception {
        int i = 0;
        Set<Class<?>> classes = getClasses("cn.freemud.entities");
        for (Class clazz : classes) {
            try {
                Object object = clazz.newInstance();
                Method[] methods = clazz.getDeclaredMethods();

                for (Method method : methods) {
                    if (method.getName().startsWith("get")) {
                        method.invoke(object);
                    } else {
                        Type[] paramType = method.getGenericParameterTypes();
                        Object paramObj = null;
                        try {
                            paramObj = Class.forName(paramType[0].getTypeName()).newInstance();
                        } catch (Exception ignore) {
                            paramObj = Class.forName(paramType[0].getTypeName()).getDeclaredConstructor(String.class).newInstance("0");
                        }
                        try {
                            method.invoke(object, paramObj);
                        } catch (Exception ignore) {
                            method.invoke(object, null);
                        }

                    }
                }
            } catch (Exception ignore) {
            }
        }
    }

    @Test
    public void classTest() throws Exception {
        int i = 0;
        Set<Class<?>> classes = getClasses("cn.freemud");
        for (Class clazz : classes) {
            try {
                Object object = clazz.newInstance();
                Method[] methods = clazz.getDeclaredMethods();

                for (Method method : methods) {

                    Type[] paramTypes = method.getGenericParameterTypes();
                    Object[] paramObjs = new Object[paramTypes.length];
                    try {
                        for (int index = 0, len = paramTypes.length; i < len; i++) {
                            Object paramObj = Class.forName(paramTypes[index].getTypeName()).newInstance();
                            paramObjs[index] = paramObj;
                        }
                    } catch (Exception ex) {

                    }

                    try {
                        method.invoke(object, paramObjs);
                    } catch (Exception ignore) {
                        method.invoke(object, null);
                    }


                }
            } catch (Exception ignore) {
            }
        }
    }

    /**
     * 从包package中获取所有的Class
     *
     * @param pack
     * @return
     */
    public static Set<Class<?>> getClasses(String pack) {
        Set<Class<?>> classes = new LinkedHashSet<Class<?>>();

        boolean recursive = true;

        String packageName = pack;
        String packageDirName = packageName.replace('.', '/');

        Enumeration<URL> dirs;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(
                    packageDirName);
            // 循环迭代下去
            while (dirs.hasMoreElements()) {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath,
                            recursive, classes);
                }
            }
        } catch (IOException e) {

        }

        return classes;
    }


    /**
     * 以文件的形式来获取包下的所有Class
     *
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    public static void findAndAddClassesInPackageByFile(String packageName,
                                                        String packagePath, final boolean recursive, Set<Class<?>> classes) {

        File dir = new File(packagePath);

        if (!dir.exists() || !dir.isDirectory()) {
            return;
        }

        File[] dirfiles = dir.listFiles(new FileFilter() {
            public boolean accept(File file) {
                return (recursive && file.isDirectory())
                        || (file.getName().endsWith(".class"));
            }
        });

        for (File file : dirfiles) {
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "."
                                + file.getName(), file.getAbsolutePath(), recursive,
                        classes);
            } else {
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                }
            }
        }
    }
}
