package com.zi.mwms.solution.tool;

import freemarker.template.Template;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ClientSolutionTool {

    private static String moduleType = "CNXsvr";

    /**
     * 业务名称 (改成你自己的) (event下的package)
     */
    private static String moduleName = "user";

    /**
     * 消息名称 (改成你自己的) (bpel消息的名称)
     */
    private static String messageName = "Test";
    
    /**
     * 是否开启事务，开启:true 关闭:false
     */
    private static boolean openTransaction = false;

    /**
     * 右键运行自动生成相关模块
     *
     * 代码类会存储在 zi-mes-be-solution 的 com.zi.mes.solution.event 里
     *
     * @param args
     */
    public static void main(String[] args) {
        try{
            String projectPath = System.getProperty("user.dir");

            if(projectPath.contains("zi-mes-lcdfab-client")){
            	projectPath = projectPath.replace("zi-mes-lcdfab-client","");
            }
            
            File bpelTemplateFile = null;
            if(openTransaction) {
            	bpelTemplateFile = new File(projectPath + "/zi-mes-lcdfab-boot/src/main/resources/template/BpelTransactionTemplate.bpel") ;
            }else {
            	bpelTemplateFile = new File(projectPath + "/zi-mes-lcdfab-boot/src/main/resources/template/BpelTemplate.bpel") ;
            }
            Reader bpelTemplateReader = new FileReader(bpelTemplateFile)  ;
            Template bpelTemplate =  new Template("", bpelTemplateReader, null);
            
            File javaEventTemplateFile = new File(projectPath + "/zi-mes-lcdfab-boot/src/main/resources/template/EventTemplate.java") ;
            Reader javaEventTemplateReader = new FileReader(javaEventTemplateFile)  ;
            Template javaEventTemplate =  new Template("", javaEventTemplateReader, null);

            File xmlConfigTemplateFile = new File(projectPath + "/zi-mes-lcdfab-boot/src/main/resources/template/XmlConfigTemplate.xml") ;
            Reader xmlConfigTemplateReader = new FileReader(xmlConfigTemplateFile)  ;
            Template xmlConfigTemplate =  new Template("", xmlConfigTemplateReader, null);

            File javaConfigTemplateFile = new File(projectPath + "/zi-mes-lcdfab-boot/src/main/resources/template/JavaConfigTemplate.java") ;
            Reader javaConfigTemplateReader = new FileReader(javaConfigTemplateFile)  ;
            Template javaConfigTemplate =  new Template("", javaConfigTemplateReader, null);

            String moduleUpperName = (new StringBuilder()).append(Character.toUpperCase(moduleName.charAt(0))).append(moduleName.substring(1)).toString();
            String eventClassName = messageName+"Event";

            Map<String,Object> bpelTemplateMap = new HashMap<String,Object>();
            bpelTemplateMap.put("name",messageName);
            bpelTemplateMap.put("eventClassName",eventClassName);
            String templateStrBpel = FreeMarkerTemplateUtils.processTemplateIntoString(bpelTemplate, bpelTemplateMap);

            Map<String,Object> javaEventTemplateMap = new HashMap<String,Object>();
            javaEventTemplateMap.put("EventPackage",moduleName);
            javaEventTemplateMap.put("EventClassName",eventClassName);
            String templateStrJava = FreeMarkerTemplateUtils.processTemplateIntoString(javaEventTemplate, javaEventTemplateMap);

            Map<String,Object> xmlConfigTemplateMap = new HashMap<String,Object>();
            String xmlConfigStrXml = FreeMarkerTemplateUtils.processTemplateIntoString(xmlConfigTemplate, xmlConfigTemplateMap);

            Map<String,Object> javaConfigTemplateMap = new HashMap<String,Object>();
            javaConfigTemplateMap.put("ModuleName",moduleName);
            javaConfigTemplateMap.put("XmlConfigName",moduleUpperName+"ServiceConfig");
            String javaConfigStrXml = FreeMarkerTemplateUtils.processTemplateIntoString(javaConfigTemplate, javaConfigTemplateMap);

            createFile(projectPath + "\\zi-mes-lcdfab-boot\\src\\main\\resources\\bpels\\"+moduleType+"\\"+messageName+".bpel",templateStrBpel);
            System.out.println("------------------------------------------ 完成创建/修改"+messageName+".bpel ------------------------------------------");
            
            createFileDic(projectPath + "\\zi-mes-lcdfab-client\\src\\main\\java\\com\\zi\\mes\\solution\\event\\"+moduleName);
            System.out.println("------------------------------------------ 完成创建/修改"+ moduleName +" ------------------------------------------");
            
            createFile(projectPath + "\\zi-mes-lcdfab-client\\src\\main\\java\\com\\zi\\mes\\solution\\event\\"+moduleName+"\\"+eventClassName+".java",templateStrJava);
            System.out.println("------------------------------------------ 完成创建/修改"+eventClassName+".java ------------------------------------------");
            
            createFile(projectPath + "\\zi-mes-lcdfab-boot\\src\\main\\resources\\service\\"+moduleName+".service.xml",xmlConfigStrXml);
            System.out.println("------------------------------------------ 完成创建/修改"+moduleName+".service.xml ------------------------------------------");
            
            createFile(projectPath + "\\zi-mes-lcdfab-boot\\src\\main\\java\\com\\zi\\mes\\solution\\config\\xml\\"+moduleUpperName+"ServiceConfig.java",javaConfigStrXml);
            System.out.println("------------------------------------------ 完成创建/修改"+moduleUpperName+"ServiceConfig.java ------------------------------------------");
            
            SAXBuilder builder = new SAXBuilder();

            Document doc = builder.build(projectPath+"\\zi-mes-lcdfab-boot\\src\\main\\resources\\service\\"+moduleName+".service.xml");

            Element root =  doc.getRootElement();

            List<Element> list = root.getChildren();

            for(Element element : list){
                if(eventClassName.equals(element.getAttribute("name").getValue())){
                    return;
                }
            }

            Element bean = new Element("bean",root.getNamespaceURI());
            bean.setAttribute(new Attribute("name",eventClassName));
            bean.setAttribute(new Attribute("class","com.zi.mes.solution.event."+moduleName+"."+eventClassName));
            root.addContent(bean);

            XMLOutputter xmlOutput = new XMLOutputter();
            Format format = Format.getRawFormat();
            format.setIndent("  ");
            format.setTextMode(Format.TextMode.TRIM_FULL_WHITE);
            xmlOutput.setFormat(format);
            xmlOutput.output(doc,new FileOutputStream(projectPath+"\\zi-mes-lcdfab-boot\\src\\main\\resources\\service\\"+moduleName+".service.xml"));
            System.out.println("------------------------------------------ It's over ------------------------------------------");
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public static Boolean createFile(String filePath,String fileContent){
        Boolean bool = false;
        File file = new File(filePath);
        try {
            if(!file.exists()){
                file.createNewFile();
                bool = true;
                writeFileContent(filePath, fileContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    public static Boolean createFileDic(String filePath){
        Boolean bool = false;
        File file = new File(filePath);
        try {
            if(!file.exists()){
                file.mkdir();
                bool = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    public static Boolean writeFileContent(String filepath,String newStr) throws IOException {
        Boolean bool = false;
        String filein = newStr + "\r\n";
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos  = null;
        PrintWriter pw = null;
        try {
            File file = new File(filepath);

            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();

            for(int i=0;(temp =br.readLine())!=null;i++){
                buffer.append(temp);
                // 行与行之间的分隔符 相当于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //不要忘记关闭
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }
}
