package xyz.wbsite.dbtool.javafx.manger.callable;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import xyz.wbsite.dbtool.javafx.manger.FreeMarkerManager;
import xyz.wbsite.dbtool.javafx.manger.ManagerFactory;
import xyz.wbsite.dbtool.javafx.po.Doc;
import xyz.wbsite.dbtool.javafx.tool.Tool;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;

public class DocCallable implements Callable {

    private File module;
    private File docFile;
    private List<Doc> docList;
    private Tool tool = new Tool();
    private FreeMarkerManager freeMarkerManager;

    public DocCallable(File module, File docFile, List<Doc> docList) {
        this.module = module;
        this.docFile = docFile;
        this.docList = docList;
        this.freeMarkerManager = ManagerFactory.getFreeMarkerManager();
    }

    public Boolean call() throws Exception {
        if (!docFile.exists()) {
            docFile.mkdir();
        } else {
            Tool.clear(docFile);
        }

        String version = "1.0";

        File file = new File(module, "pom.xml");

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        Document document = documentBuilderFactory.newDocumentBuilder().parse(file);

        Element documentElement = document.getDocumentElement();
        NodeList childNodes = documentElement.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node item = childNodes.item(i);
            if (item.getNodeName().equals("version")) {
                version = item.getTextContent();
            }
        }

        File js = Tool.createPath(this.docFile, "js");
        File css = Tool.createPath(this.docFile, "css");

        Tool.outputResource("Doc/js/index.js", Tool.createFile(js, "index.js"));
        Tool.outputResource("Doc/js/vue.min.js", Tool.createFile(js, "vue.min.js"));
        Tool.outputResource("Doc/css/index.css", Tool.createFile(css, "index.css"));
        Tool.outputResource("Doc/index.html", Tool.createFile(this.docFile, "index.html"));

        File api = Tool.createFile(js, "index.js");
        HashMap<String, Object> ctx = new HashMap<String, Object>();
        ctx.put("docList", docList);
        freeMarkerManager.outputTemp(api, "Doc/js/index.js", ctx);

        System.out.println("finish");
        return true;
    }

}
