package net.northking.cctp.element.scanner;



import net.northking.cctp.element.core.ContextInitializer;
import net.northking.cctp.element.core.Library;
import net.northking.cctp.element.core.scanner.LibraryDefinition;
import net.northking.cctp.element.log.Slf4jLogger;
import net.northking.cctp.element.util.Assert;
import net.northking.cctp.element.validation.Constraint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.net.URL;

/**
 * Keyword jar scanner
 *
 * @author fengxiang.zhang
 * @since 1.0
 */
public class JarLibraryScanner {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(JarLibraryScanner.class);

    public static Library scan(String jar) throws Exception {
        logger.debug("Load jar: {}", jar);
        Assert.endsWith(jar, ".jar");
        return scanSource(jar);
    }

    public static Library scan(URL jarURL) throws Exception {
        logger.debug("Load jar URL: {}", jarURL);
        Assert.notNull(jarURL);
        Assert.endsWith(jarURL.toString(), ".jar");
        return scanSource(jarURL);
    }

    public static Library scan(InputStream jarStream) throws Exception {
        logger.debug("Load jar stream.");
        return scanSource(jarStream);
    }

    private static Library scanSource(Object source) throws Exception {
        LibraryDefinition definition = LibraryLoadHelper.load(source);
        ContextInitializer initializer = new ContextInitializer();
        initializer.setLibraryDefinition(definition)
                .setOnlyScan(true)
                .registerBean(Logger.class, new Slf4jLogger());
        return Constraint.wrap(initializer.initialize().getLibrary());
    }
}