package org.bdware.sc.engine.hook;

import org.bdware.sc.JSEngine;
import org.bdware.sc.bean.ContractRequest;
import org.bdware.sc.engine.DesktopEngine;
import org.bdware.sc.node.AnnotationHook;
import org.bdware.sc.node.ArgPacks;
import org.commonmark.node.FencedCodeBlock;
import org.commonmark.node.Heading;
import org.commonmark.node.Node;
import org.commonmark.node.Text;
import org.commonmark.parser.Parser;

public class ReadMeHandler implements AnnotationHook {
    String getReadMeData(DesktopEngine desktopEngine, ContractRequest c) {
        String fileReadme =
                desktopEngine
                        .getResources()
                        .loadAsString("/assets/README.md"); // is "/README.md"  not"./README.md"!!!!
        // System.out.println("fileReadme:" + fileReadme);
        if (null == fileReadme) {
            return "项目目录下无预览文档";
        } else {
            String result = "未能返回调试调用结果";
            String targetFunction = c.getAction();
            try {
                Parser parser = Parser.builder().build();
                Node document = parser.parse(fileReadme);
                Node visitor = document.getFirstChild();
                while (visitor != null) {
                    if (visitor instanceof Heading) {
                        if (((Heading) visitor).getLevel() == 2) {
                            if (((Text) (visitor.getFirstChild()))
                                    .getLiteral()
                                    .equals(targetFunction)) {
                                FencedCodeBlock blockResult =
                                        (FencedCodeBlock)
                                                (visitor.getNext()
                                                        .getNext()
                                                        .getNext()
                                                        .getNext()
                                                        .getNext()
                                                        .getNext()
                                                        .getNext());
                                result = blockResult.getLiteral();
                                break;
                            }
                        }
                    }
                    visitor = visitor.getNext();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    }

    @Override
    public ArgPacks handle(JSEngine engine, ArgPacks argPacks) {
        DesktopEngine desktopEngine = (DesktopEngine) engine;
        ContractRequest input = argPacks.request;

        if (input.fromDebug() && (argPacks.ret == null || argPacks.ret.equals("emptyMock"))) {
            argPacks.ret = getReadMeData(desktopEngine, input);
            System.out.println(argPacks.ret);
        }
        return argPacks;
    }
}
