package com.izouma.codegenerator;


import com.izouma.awesomeadmin.model.GenCode;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.tools.ToolManager;
import org.hibernate.validator.internal.util.privilegedactions.GetResource;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.*;

public class ControllerGenerator {
    /**
     * 生成Controller
     *
     * @param model
     */
    public static void GenController(GenCode model) {
        try {
            List<String> imports = new ArrayList<>();
            imports = GeneratorTool.removeDuplicated(imports);

            String templatePath = GetResource.class.getClassLoader().getResource("templates").getPath();
            Properties pro = new Properties();
            pro.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
            pro.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, templatePath);
            Velocity.init(pro);
            ToolManager manager = new ToolManager(true, true);
            VelocityContext context = new VelocityContext(manager.createContext());
            context.put("imports", imports);
            context.put("model", model);
            Template t = Velocity.getTemplate("ControllerTemplate.vm");

            String targetFile = model.getClassName() + "Controller.java";
            File file = new File(model.getJavaPath() + "/web", targetFile);
            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();
            if (!file.exists())
                file.createNewFile();

            FileOutputStream outStream = new FileOutputStream(file);
            OutputStreamWriter writer = new OutputStreamWriter(outStream,
                    "UTF-8");
            BufferedWriter sw = new BufferedWriter(writer);
            t.merge(context, sw);
            sw.flush();
            sw.close();
            outStream.close();
            System.out.println("成功生成Controller:" + file.getAbsolutePath());

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