package org.generator;

import com.google.common.base.CaseFormat;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.*;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultCommentGenerator;
import org.mybatis.generator.internal.DefaultShellCallback;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

/**
 * @program: ShSecpSystem
 * @description: 生成器程序
 * @author: fengjun
 * @create: 2021-10-30
 */
public class GeneratorStarter {
    public static void generate(String tableName, JdbcParams jdbc) throws XMLParserException, SQLException, IOException, InterruptedException, InvalidConfigurationException {
        HashMap<String, String> tableConfig = new HashMap<String, String>();
        String upperBeanName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName);
        tableConfig.put("tableName", tableName);
        tableConfig.put("domainObjectName", upperBeanName);
        stater(tableConfig, jdbc);
    }

    public static void generate(String tableName, String schema, JdbcParams jdbc) throws XMLParserException, SQLException, IOException, InterruptedException, InvalidConfigurationException {
        HashMap<String, String> tableConfig = new HashMap<String, String>();
        String upperBeanName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName);
        tableConfig.put("tableName", tableName);
        tableConfig.put("domainObjectName", upperBeanName);
        tableConfig.put("schema", schema);
        stater(tableConfig, jdbc);
    }

    private static void stater(HashMap<String, String> tableConfig, JdbcParams jdbc) throws XMLParserException, IOException, SQLException, InterruptedException, InvalidConfigurationException {
        String configFileName = "mybatisGen.xml";
        List<String> warnings = new ArrayList<>();
//        System.out.println(configFileName);
//        String rfp = GeneratorMain.class.getResource("/" + configFileName).getFile();
//        File configFile = new File(rfp);
//        ConfigurationParser cp = new ConfigurationParser(warnings);
//        Configuration config = cp.parseConfiguration(configFile);
        Configuration config = new Configuration();
        DefaultShellCallback callback = new DefaultShellCallback(true);
        MyBatisGenerator myBatisGenerator;
        //hashmap
        setConfiguration(config, tableConfig, jdbc);
        myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }

    private static void setConfiguration(Configuration cft, HashMap<String, String> tableConfig, JdbcParams jdbc) {
        if (cft != null) {

            Context context = new Context(ModelType.CONDITIONAL);
            cft.addContext(context);
            context.setId("mbg");
            context.setTargetRuntime("MyBatis3");

            TableConfiguration tableConf = new TableConfiguration(context);
            //设置表名
            String tableName = tableConfig.get("tableName");
            if (tableName != null && !"".equals(tableName)) {
                tableConf.setTableName(tableName);
            }
            //如果有用户名 需要设置用户名
            if (tableConfig.containsKey("schema")) {
                tableConf.setSchema(tableConfig.get("schema"));
            }
            //设置生成的实体类的名称
            String domainObjectName = tableConfig.get("domainObjectName");
            if (domainObjectName != null && !"".equals(domainObjectName)) {
                tableConf.setDomainObjectName(domainObjectName);
            }
            tableConf.setCountByExampleStatementEnabled(false);
            tableConf.setDeleteByExampleStatementEnabled(false);
            tableConf.setSelectByExampleStatementEnabled(false);
            tableConf.setUpdateByExampleStatementEnabled(false);
            context.addTableConfiguration(tableConf);

            //数据库

            JDBCConnectionConfiguration jdbcConnection = new JDBCConnectionConfiguration();
            jdbcConnection.setDriverClass(jdbc.getDriveClass());
            jdbcConnection.setConnectionURL(jdbc.getUrl());
            jdbcConnection.setUserId(jdbc.getUsername());
            jdbcConnection.setPassword(jdbc.getPassword());
//                https://mybatis.org/generator/usage/mysql.html
            jdbcConnection.getProperties().setProperty("nullCatalogMeansCurrent", "true");
            context.setJdbcConnectionConfiguration(jdbcConnection);

            //java实体类配置
            JavaModelGeneratorConfiguration javaMode = new JavaModelGeneratorConfiguration();
            //设置model实体类对应的包路径，以及文件存放路径 targetProject可以指定具体的路径,如./src/main/java
            javaMode.setTargetPackage(GeneratorMain.POJO_PACKAGE);
            javaMode.setTargetProject(GeneratorMain.BASE_PATH + "java");
            javaMode.getProperties().setProperty("enableSubPackages", "false");
            javaMode.getProperties().setProperty("trimStrings", "true");
//                javaMode.getProperties().setProperty("rootClass", "com.ag.dynamicmodule.service.BaseEntiy");
            context.setJavaModelGeneratorConfiguration(javaMode);

            //对应的mapper.xml文件
            SqlMapGeneratorConfiguration sqlMap = new SqlMapGeneratorConfiguration();
            sqlMap.setTargetPackage(".");
            sqlMap.setTargetProject(GeneratorMain.SQL_PROJECT);
            sqlMap.getProperties().setProperty("enableSubPackages", "false");
            context.setSqlMapGeneratorConfiguration(sqlMap);

            //对应mapper接口
            JavaClientGeneratorConfiguration javaClient = new JavaClientGeneratorConfiguration();
            javaClient.setTargetPackage(GeneratorMain.DOMAIN_PACKAGE + ".mapper");
            javaClient.setTargetProject(GeneratorMain.BASE_PATH + "java");
            javaClient.setConfigurationType("XMLMAPPER");
            context.setJavaClientGeneratorConfiguration(javaClient);
        }
    }

}
