package me.chyxion.tigon.codegen.service;

import java.io.File;
import java.util.Map;
import java.util.List;
import org.apache.commons.io.FileUtils;
import java.nio.charset.StandardCharsets;
import me.chyxion.tigon.codegen.CodeGenCustomizer;
import me.chyxion.tigon.codegen.model.CodeGenArgs;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Oct 6, 2014 1:10:55 PM
 */
public abstract class CodeGenerator {
    @Autowired(required = false)
    private List<CodeGenCustomizer> customizers;
    @Autowired
    protected CodeGenBaseTool baseTool;
    protected String codeDir = "src/main/java/";
    protected String testDir = "src/test/java/";
    protected String resourcesDir = "src/main/resources/";
    protected String viewsDir = "src/main/webapp/assets/js/views/";

    /**
     * @param dataModel
     * @param module
     * @param model
     */
    public abstract String process(Map<String, Object> dataModel, String module, String model);

    /**
     * @param dataModel
     * @return
     */
    public boolean accept(Map<String, Object> dataModel) {
        return true;
    }

    /**
     * render FreeMarker Tpl
     * @param args code gen args
     * @return gen result file path
     */
    protected String render(CodeGenArgs args) {
        try {
            // customize
            if (customizers != null && customizers.size() > 0) {
                for (CodeGenCustomizer customizer : customizers) {
                    customizer.customize(args);
                }
            }
            // write result
            FileUtils.write(new File(baseTool.getProjDir(), args.getFile()), 
                baseTool.renderFtl(args.getFtl(), args.getModel()), 
                StandardCharsets.UTF_8);
            return args.getFile();
        }
        catch (Exception e) {
            throw new IllegalStateException(
                "Code Gen Render File Error Caused.", e);
        }
    }
}
