package com.cftech.core.mybatis.mybatis;


import org.apache.commons.lang3.StringUtils;


/**
 * Created by lisw on 2016-08-05
 */
public class RestControllerGenerator extends AbstractMybatisGenerator {

    @Override
    public void outputJavaCode(TableBean tableBean) {
        if (tableBean != null) {
            String rootPath = "";
            if (StringUtils.isBlank(rootPath)) {
                rootPath = System.getProperty("user.dir");
            }
            if (!rootPath.endsWith("/src/main/java") || !rootPath.endsWith("src/main/java/")) {
                if (rootPath.endsWith("/")) {
                    rootPath += "src/main/java/";
                } else {
                    rootPath += "/src/main/java/";
                }
            }
            String basePackage = tableBean.getBasePackage();

            String filePath = rootPath + basePackage.replace(pointStr, "/") + "/";
            String entityName = tableBean.getEntityName();
            String modelPackage = tableBean.getPackageName();
            String restFilePath = filePath + "rest/" + entityName + "RestController.java";
            outputJavaFile(restFilePath, generateRestController(basePackage, modelPackage, entityName).toString());

        }
    }

    /**
     * generateRestController
     *
     * @param basePackage
     * @param modelPackage
     * @param entityName
     * @return StringBuffer
     */
    public StringBuffer generateRestController(String basePackage, String modelPackage, String entityName) {
        StringBuffer sb = new StringBuffer();
        String clazzSimpleName = entityName;
        String clazzNameLower = clazzSimpleName.substring(0, 1).toLowerCase() + clazzSimpleName.substring(1);

        String suffix = "rest";
        String restSuffix = "RestController";
        sb.append("package ").append(basePackage).append(pointStr).append(suffix).append(semicolon).append(enter);
        sb.append(enter);
        sb.append("import org.springframework.web.bind.annotation.RequestMapping;").append(enter);
        sb.append("import org.springframework.web.bind.annotation.RestController;").append(enter);
        sb.append(enter);
        sb.append("import com.confucian.framework.web.AbstractRestController;").append(enter);
        sb.append(enter);
        sb.append("/**").append(enter);
        sb.append(" * ").append(clazzNameLower).append(restSuffix).append(enter);
        sb.append(" * @author ice").append(enter);
        sb.append(" */").append(enter);
        sb.append("@RestController").append(enter);
        sb.append("@RequestMapping(\"/").append(clazzNameLower).append("\")").append(enter);
        sb.append("public class ").append(clazzSimpleName).append(restSuffix);
        sb.append(" extends AbstractRestController {").append(enter);
        sb.append(enter);
        sb.append("}").append(enter);
        return sb;
    }

}
