package net.northking.cctp.element.test;

import net.northking.cctp.element.core.IExecuteContext;
import net.northking.cctp.element.core.Library;
import net.northking.cctp.element.core.LibraryContext;
import net.northking.cctp.element.core.ContextInitializer;
import net.northking.cctp.element.core.scanner.LibraryDefinition;
import net.northking.cctp.element.core.scanner.ResourceScanner;
import net.northking.cctp.element.core.support.PathMatchingResourceResolver;
import net.northking.cctp.element.log.Slf4jLogger;
import net.northking.cctp.element.validation.Constraint;
import org.slf4j.LoggerFactory;

/**
 * Test class should inherits this class
 *
 * <pre>
 * public class StringUtilsLibraryTest extends AbstractLibraryTest {
 *
 * 	&#64;Autowired
 * 	private AtpStringKeyword atpStringKeyword;
 *
 * 	&#64;Test
 * 	public void test() {
 * 		assertTrue("xxxx".equals(atpStringKeyword.lowerCase("XXXX")));
 *    }
 *
 * 	&#64;Test
 * 	public void test2() throws Exception {
 * 		ParamsBuilder builder = new ParamsBuilder();
 * 		builder.add("str", "aaa");
 * 		Object result = this.library.runKeyword("upperCase", builder.build());
 * 		assertTrue("AAA".equals(result.toString()));
 *    }
 * }
 * </pre>
 *
 * @author fengxiang.zhang
 * @since 1.0
 */
public abstract class AbstractLibraryTest {

    private static org.slf4j.Logger logger = LoggerFactory.getLogger(AbstractLibraryTest.class);
    private static LibraryDefinition definition;
    protected LibraryContext context;
    protected Library library;

    static {
        logger.debug("AbstractLibraryTest类初始化开始.");
        loadInitialLibraries();
        logger.debug("AbstractLibraryTest类初始化完成.");
    }

    private static void loadInitialLibraries() {
        try {
            logger.debug("正在加载组件库...");
            ResourceScanner scanner = new ResourceScanner();
            scanner.setResourceLoader(new PathMatchingResourceResolver());
            definition = scanner.doScan();
            logger.debug("组件库加载完成.");
        } catch (Exception e) {
            logger.error("加载组件库失败", e);
        }
    }

    public AbstractLibraryTest() {
        try {
            context = new ContextInitializer()
                    .setLibraryDefinition(definition)
                    .registerLogger(new Slf4jLogger())
                    .registerBean(this)
                    .registerBean(IExecuteContext.class, new SampleExecuteContext.Builder().build())
                    .initialize();
            library = Constraint.wrap(context.getLibrary());
        } catch (Exception e) {
            logger.error("初始化库上下文失败", e);
        }
    }

    public Library getLibrary() {
        return library;
    }

    public LibraryContext getContext() {
        return context;
    }
}