package org.bdware.sc.parser;

import com.google.gson.Gson;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.DiagnosticErrorListener;
import org.bdware.sc.compiler.YJSCompiler;
import org.bdware.sc.compiler.YJSErrorListener;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.ContractNode;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class YJSParserTest {
    @Test
    public void elseTest() throws IOException {
        InputStream resource = YJSParserTest.class.getClassLoader().getResourceAsStream("module1.yjs");
        JavaScriptLexer lexer;
        assert resource != null;
        lexer = new JavaScriptLexer(CharStreams.fromStream(resource));
        lexer.setUseStrictDefault(true);
        CommonTokenStream cts = new CommonTokenStream(lexer);
        YJSErrorListener errorListener = new YJSErrorListener();
        // 语法分析
        YJSParser parser = new YJSParser(cts);
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.addErrorListener(new DiagnosticErrorListener());
        YJSParser.ProgramContext tree = parser.program();
        for (String str : errorListener.getResultList())
            System.out.println(str);
    }

    @Test
    public void functionTest() throws IOException {
        InputStream resource = YJSParserTest.class.getClassLoader().getResourceAsStream("function.yjs");
        JavaScriptLexer lexer;
        assert resource != null;
        lexer = new JavaScriptLexer(CharStreams.fromStream(resource));
        lexer.setUseStrictDefault(true);
        CommonTokenStream cts = new CommonTokenStream(lexer);
        YJSErrorListener errorListener = new YJSErrorListener();
        // 语法分析
        YJSParser parser = new YJSParser(cts);
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.addErrorListener(new DiagnosticErrorListener());
        YJSParser.ProgramContext tree = parser.program();
        for (YJSParser.ClzOrFunctionDeclarationContext clzOrFunc : tree.contractDeclar().clzOrFunctionDeclaration()) {
            System.out.println(clzOrFunc.functionDeclaration().View());
        }
        for (String str : errorListener.getResultList()) {
            System.out.println(str);
        }
    }

    @Test
    public void test() throws FileNotFoundException {//测试执行 engine 的 executeContract方法
        InputStream resource = new FileInputStream(
                "../front-agent/BDWareProjectDir/public/ARouteExample/ARouteExample.yjs");
        YJSCompiler compiler = new YJSCompiler();
        try {
            ContractNode cn = compiler.compile(resource, "rrr.yjs");
            new DesktopEngine();
            System.out.println(new Gson().toJson(cn));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
