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

import xyz.wbsite.dbtool.javafx.manger.FreeMarkerManager;
import xyz.wbsite.dbtool.javafx.manger.ManagerFactory;
import xyz.wbsite.dbtool.javafx.manger.ProjectManager;
import xyz.wbsite.dbtool.javafx.po.AbstractDBmapper;
import xyz.wbsite.dbtool.javafx.po.Api;
import xyz.wbsite.dbtool.javafx.tool.EntityReader;
import xyz.wbsite.dbtool.javafx.tool.RequestReader;
import xyz.wbsite.dbtool.javafx.tool.ResponseReader;
import xyz.wbsite.dbtool.javafx.tool.Tool;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ApiCallable implements Callable {

    private File module;
    private File apiFile;
    private List<Api> apiList;
    private List<String> domainList;
    private Tool tool = new Tool();

    private FreeMarkerManager freeMarkerManager;

    public ApiCallable(File module, File apiFile, List<String> domainList, List<Api> apiList) {
        this.module = module;
        this.apiFile = apiFile;
        this.apiList = apiList;
        this.domainList = domainList;
        this.freeMarkerManager = ManagerFactory.getFreeMarkerManager();
    }

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

        AbstractDBmapper dBmapper = ProjectManager.dBmapper;

        File domain;
        File testdomain;

        StringBuffer sbmain = new StringBuffer("");
        sbmain.append(this.apiFile.getPath() + File.separator);
        sbmain.append("src" + File.separator);
        sbmain.append("main" + File.separator);
        sbmain.append("java" + File.separator);

        StringBuffer sbtest = new StringBuffer("");
        sbtest.append(this.apiFile.getPath() + File.separator);
        sbtest.append("src" + File.separator);
        sbtest.append("test" + File.separator);
        sbtest.append("java" + File.separator);

        for (String s1 : domainList) {
            sbmain.append(s1 + File.separator);
            sbtest.append(s1 + File.separator);
        }

        domain = new File(sbmain.toString());
        domain.mkdirs();
        testdomain = new File(sbtest.toString());
        testdomain.mkdirs();

        for (Api api : apiList) {
            if (api.isCheck()) {
                File apiModule = new File(domain, api.getModule());
                apiModule.mkdirs();
                File apiRequest = new File(apiModule, "req");
                apiRequest.mkdirs();
                File apiResponse = new File(apiModule, "rsp");
                apiResponse.mkdirs();
                File entity = new File(apiModule, "ent");
                entity.mkdirs();

                try {
                    //region 生成request
                    RequestReader requestReader = new RequestReader(api.getRequestFile());
                    for (int i = 0; i < requestReader.getImportList().size(); i++) {
                        String s = requestReader.getImportList().get(i);
                        if (s.contains(".module.entity.")) {
                            requestReader.getImportList().set(i, s);
                        }
                    }

                    List<String> entNames = new ArrayList<>();

                    for (String s : requestReader.getDeptEntList()) {
                        Pattern compile = Pattern.compile("(.*\\.ent)\\.(.*)");
                        Matcher matcher = compile.matcher(s);

                        if (matcher.find()) {
                            String Package = matcher.group(1);
                            String EntName = matcher.group(2);
                            entNames.add(EntName);

                            List<File> files = Tool.find(this.module, EntName + ".java");

                            for (File file : files) {
                                EntityReader entReader = new EntityReader(file);
                                if (Package.equals(entReader.getPackageName())) {
                                    HashMap<String, Object> ctx = new HashMap<String, Object>();
                                    ctx.put("package", "package " + entReader.getDomainName() + "." + entReader.getModuleName() + "." + "req;");
                                    ctx.put("domain", entReader.getDomainName());
                                    ctx.put("module", entReader.getModuleName());
                                    ctx.put("importList", entReader.getImportList());
                                    ctx.put("annotation", entReader.getAnnotationList());
                                    ctx.put("className", entReader.getClassName().replaceAll("Entity", ""));
                                    ctx.put("body", entReader.getBody());
                                    ctx.put("tool", tool);
                                    File EntFile = new File(entity.getAbsolutePath(), EntName + ".java");
                                    freeMarkerManager.outputTemp(EntFile, "Java_api/module/ent/entity.java", ctx);
                                    System.out.println("生成文件" + EntName + "成功");
                                }
                            }

                        }
                    }

                    List<String> reqNames = new ArrayList<>();

                    for (String s : requestReader.getDeptReqList()) {
                        Pattern compile = Pattern.compile("(.*\\.req)\\.(.*)");
                        Matcher matcher = compile.matcher(s);

                        if (matcher.find()) {
                            String Package = matcher.group(1);
                            String EntName = matcher.group(2);
                            reqNames.add(EntName);

                            List<File> files = Tool.find(this.module, EntName + ".java");

                            for (File file : files) {
                                RequestReader reqReader = new RequestReader(file);
                                if (Package.equals(reqReader.getPackageName())) {
                                    HashMap<String, Object> ctx = new HashMap<String, Object>();
                                    ctx.put("package", "package " + requestReader.getDomainName() + "." + requestReader.getModuleName() + "." + "req;");
                                    ctx.put("domain", requestReader.getDomainName());
                                    ctx.put("module", requestReader.getModuleName());
                                    ctx.put("target", api.getTarget());
                                    ctx.put("method", api.getMethod());
                                    ctx.put("importList", requestReader.getImportList());
                                    ctx.put("entNames", entNames);
                                    ctx.put("annotation", requestReader.getAnnotationList());
                                    ctx.put("className", requestReader.getClassName().replaceAll("Request", ""));
                                    ctx.put("body", requestReader.getBody());
                                    ctx.put("tool", tool);
                                    ctx.put("hasList", requestReader.isHasList());
                                    ctx.put("findOrSearchflag", requestReader.getFindOrSearchflag());
                                    File reqfile = new File(apiRequest.getAbsolutePath(), api.getRequestFile().getName());

                                    freeMarkerManager.outputTemp(reqfile, "Java_api/module/req/request.java", ctx);
                                    System.out.println("生成文件" + reqfile.getName() + "成功");
                                }
                            }

                        }
                    }

                    {
                        HashMap<String, Object> ctx = new HashMap<String, Object>();
                        ctx.put("package", "package " + requestReader.getDomainName() + "." + requestReader.getModuleName() + "." + "request;");
                        ctx.put("domain", requestReader.getDomainName());
                        ctx.put("module", requestReader.getModuleName());
                        ctx.put("target", api.getTarget());
                        ctx.put("method", api.getMethod());
                        ctx.put("importList", requestReader.getImportList());
                        ctx.put("entNames", entNames);
                        ctx.put("reqNames", reqNames);
                        ctx.put("annotation", requestReader.getAnnotationList());
                        ctx.put("className", requestReader.getClassName().replaceAll("Request", ""));
                        ctx.put("body", requestReader.getBody());
                        ctx.put("tool", tool);
                        ctx.put("hasList", requestReader.isHasList());
                        ctx.put("findOrSearchflag", requestReader.getFindOrSearchflag());
                        File file = new File(apiRequest.getAbsolutePath(), api.getRequestFile().getName());

                        freeMarkerManager.outputTemp(file, "Java_api/module/req/request.java", ctx);
                        System.out.println("生成文件" + file.getName() + "成功");
                    }
                    //endregion
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {
                    //region 生成response
                    ResponseReader responseReader = new ResponseReader(api.getResponseFile());
                    for (int i = 0; i < responseReader.getImportList().size(); i++) {
                        String import_ = responseReader.getImportList().get(i);
                        if (import_.contains(".module.entity.")) {
                            responseReader.getImportList().set(i, import_);
                        }
                    }

                    List<String> entNames = new ArrayList<>();

                    for (String s : responseReader.getDeptEntList()) {
                        Pattern compile = Pattern.compile("(.*\\.ent)\\.(.*)");
                        Matcher matcher = compile.matcher(s);

                        if (matcher.find()) {
                            String Package = matcher.group(1);
                            String EntName = matcher.group(2);
                            entNames.add(EntName);

                            List<File> files = Tool.find(this.module, EntName + ".java");

                            for (File file : files) {
                                EntityReader entReader = new EntityReader(file);
                                if (Package.equals(entReader.getPackageName())) {
                                    HashMap<String, Object> ctx = new HashMap<String, Object>();
                                    ctx.put("package", "package " + entReader.getDomainName() + "." + entReader.getModuleName() + "." + "request;");
                                    ctx.put("domain", entReader.getDomainName());
                                    ctx.put("module", entReader.getModuleName());
                                    ctx.put("importList", entReader.getImportList());
                                    ctx.put("annotation", entReader.getAnnotationList());
                                    ctx.put("className", entReader.getClassName().replaceAll("Entity", ""));
                                    ctx.put("body", entReader.getBody());
                                    ctx.put("tool", tool);
                                    File EntFile = new File(entity.getAbsolutePath(), EntName + ".java");
                                    freeMarkerManager.outputTemp(EntFile, "Java_api/module/ent/entity.java", ctx);
                                    System.out.println("生成文件" + EntName + "成功");
                                }
                            }

                        }
                    }

                    {
                        HashMap<String, Object> ctx = new HashMap<String, Object>();
                        ctx.put("package", "package " + responseReader.getDomainName() + "." + responseReader.getModuleName() + "." + "request;");
                        ctx.put("domain", responseReader.getDomainName());
                        ctx.put("module", responseReader.getModuleName());
                        ctx.put("importList", responseReader.getImportList());
                        ctx.put("entNames", entNames);
                        ctx.put("annotation", responseReader.getAnnotationList());
                        ctx.put("className", responseReader.getClassName().replaceAll("Response", ""));
                        ctx.put("body", responseReader.getBody());
                        ctx.put("tool", tool);
                        ctx.put("hasList", responseReader.isHasList());
                        ctx.put("Tclass", responseReader.getTclass());
                        File file = new File(apiResponse.getAbsolutePath(), api.getResponseFile().getName().replaceAll("Request", "Response"));

                        freeMarkerManager.outputTemp(file, "Java_api/module/rsp/response.java", ctx);
                        System.out.println("生成文件" + api.getResponseFile().getName() + "成功");
                    }
                    //endregion


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


        {
            System.out.println("生成模块:Pom");
            HashMap<String, Object> ctx = new HashMap<String, Object>();
            ctx.put("module", apiFile.getName());
            File file = new File(apiFile, "pom.xml");
            freeMarkerManager.outputTemp(file, "Java_api/pom.xml", ctx);
        }

        {
            System.out.println("生成基础类");
            HashMap<String, Object> ctx = new HashMap<String, Object>();
            ctx.put("domain", String.join(".", domainList));
            {
                File file = new File(domain, "ApiEntity.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ApiEntity.java", ctx);
            }
            {
                File file = new File(domain, "AESUtil.java");
                freeMarkerManager.outputTemp(file, "/Java_api/AESUtil.java", ctx);
            }
            {
                File file = new File(domain, "ApiClient.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ApiClient.java", ctx);
            }
            {
                File file = new File(domain, "ApiRequest.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ApiRequest.java", ctx);
            }
            {
                File file = new File(domain, "ApiFindRequest.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ApiFindRequest.java", ctx);
            }
            {
                File file = new File(domain, "ApiSearchRequest.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ApiSearchRequest.java", ctx);
            }
            {
                File file = new File(domain, "ApiResponse.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ApiResponse.java", ctx);
            }
            {
                File file = new File(domain, "ApiFindResponse.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ApiFindResponse.java", ctx);
            }
            {
                File file = new File(domain, "Base64Util.java");
                freeMarkerManager.outputTemp(file, "/Java_api/Base64Util.java", ctx);
            }
            {
                File file = new File(domain, "DownloadUtil.java");
                freeMarkerManager.outputTemp(file, "/Java_api/DownloadUtil.java", ctx);
            }
            {
                File file = new File(domain, "Error.java");
                freeMarkerManager.outputTemp(file, "/Java_api/Error.java", ctx);
            }
            {
                File file = new File(domain, "ErrorType.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ErrorType.java", ctx);
            }
            {
                File file = new File(domain, "MapperUtil.java");
                freeMarkerManager.outputTemp(file, "/Java_api/MapperUtil.java", ctx);
            }
            {
                File file = new File(domain, "MD5Util.java");
                freeMarkerManager.outputTemp(file, "/Java_api/MD5Util.java", ctx);
            }
            {
                File file = new File(domain, "RSAUtil.java");
                freeMarkerManager.outputTemp(file, "/Java_api/RSAUtil.java", ctx);
            }
            {
                File file = new File(domain, "ProgressRequestBody.java");
                freeMarkerManager.outputTemp(file, "/Java_api/ProgressRequestBody.java", ctx);
            }

            {
                File file = new File(domain, "SortType.java");
                freeMarkerManager.outputTemp(file, "/Java_api/SortType.java", ctx);
            }

            {
                File file = new File(domain, "StringUtils.java");
                freeMarkerManager.outputTemp(file, "/Java_api/StringUtils.java", ctx);
            }

            //4.0.1 去掉验证 减少体积
//        {
//            File file = new File(frameWork , "ValidationUtil.java");
//            freeMarkerManager.outputTemp(file, "/Java_api/ValidationUtil.java", ctx);
//        }

        }

        {//生成Test
            System.out.println("生成模块:Test");
            HashMap<String, Object> ctx = new HashMap<String, Object>();
            ctx.put("tool", tool);
            ctx.put("domain", String.join(".", domainList));
            ctx.put("apiList", apiList);
            freeMarkerManager.outputTemp(new File(testdomain.getAbsolutePath(), "ApiTest.java"), "Java_api/ApiTest.java", ctx);
        }

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