package com.pictc.config;

import java.io.IOException;
import java.io.InputStream;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ScanConfig {
	
	
	public static final String AUTO_FILE_NAME="auto-scan.txt";
	
	private static final String FILE_PROCOTOL="file";
	
	private static final String JAR_PROCOTOL="jar";
	
	private static ClassLoader getDefaultClassLoader() {
		ClassLoader cl = null;
		try {
			cl = Thread.currentThread().getContextClassLoader();
		}
		catch (Throwable ex) {}
		if (cl == null) {
			cl = ScanConfig.class.getClassLoader();
			if (cl == null) {
				try {
					cl = ClassLoader.getSystemClassLoader();
				}
				catch (Throwable ex) {}
			}
		}
		return cl;
	}
	
	public static void scan(String name,ScanFilter filter) {
		try {
			Enumeration<URL> dirs = getDefaultClassLoader().getResources(name);
			if(dirs!=null) {
				while(dirs.hasMoreElements()) {
					URL url = dirs.nextElement();
					if(FILE_PROCOTOL.equals(url.getProtocol())) {
						filter.accept(readConf(url.openStream()));
					}else if(JAR_PROCOTOL.equals(url.getProtocol())) {
						JarFile jarFile = ((JarURLConnection)url.openConnection()).getJarFile();
						ZipEntry entry = jarFile.getEntry(name);
						if(entry!=null) {
							filter.accept(readConf(jarFile.getInputStream(entry)));
						}
					}
				}
			}else {
				log.info("没有扫描到任何东西！");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private static Properties readConf(InputStream in) {
		Properties pro = new Properties();
		try {
			pro.load(in);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("读取配置文件错误");
		}
		return pro;
	}
	
	public static void scanConfig(ScanFilter filter) {
		scan(AUTO_FILE_NAME,filter);
	}
	
	
	public interface ScanFilter{
		
		public void accept(Properties conf);
	}

}
