package com.starry.generator;

import com.starry.generator.config.GeneratorConfig;
import com.starry.generator.core.CodeGenerator;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 代码生成器主类 - 支持配置文件版本 通过读取 config.properties 配置文件来生成代码
 *
 * @author admin
 * @since 2024-01-01
 */
public class MainGeneratorWithConfig {

    public static void main(String[] args) {
        try {
            // 读取配置文件
            GeneratorConfig config = loadConfig();

            // 获取要生成的表名
            String tableNamesStr = getProperty("gen.tableNames", "");
            if (tableNamesStr.isEmpty()) {
                System.err.println("错误：未配置要生成的表名，请在 config.properties 中设置 gen.tableNames");
                return;
            }
            String[] tableNames = tableNamesStr.split(",");

            // 清理表名（去除前后空格）
            for (int i = 0; i < tableNames.length; i++) {
                tableNames[i] = tableNames[i].trim();
            }

            // 创建代码生成器并执行生成
            CodeGenerator generator = new CodeGenerator(config);

            System.out.println("=== 代码生成器配置信息 ===");
            System.out.println("数据库地址: " + config.getUrl());
            System.out.println("包名: " + config.getPackageName());
            System.out.println("输出目录: " + config.getOutputDir());
            System.out.println("作者: " + config.getAuthor());
            System.out.println("要生成的表: " + String.join(", ", tableNames));
            System.out.println("========================");
            System.out.println();

            System.out.println("开始生成代码...");
            generator.generateCode(tableNames);
            System.out.println();
            System.out.println("代码生成完成！输出目录：" + config.getOutputDir());

        } catch (Exception e) {
            System.err.println("代码生成失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private static Properties properties;

    private static GeneratorConfig loadConfig() throws IOException {
        // 加载配置文件
        properties = new Properties();
        try (InputStream input = MainGeneratorWithConfig.class.getClassLoader()
                .getResourceAsStream("config.properties")) {
            if (input == null) {
                throw new IOException("配置文件 config.properties 未找到");
            }
            properties.load(input);
        }

        // 创建配置对象
        GeneratorConfig config = new GeneratorConfig();

        // 数据库配置
        config.setUrl(getProperty("db.url", ""));
        config.setDatabaseName(getProperty("db.name", ""));
        config.setDriverName(getProperty("db.driver", "com.mysql.cj.jdbc.Driver"));
        config.setUsername(getProperty("db.username", ""));
        config.setPassword(getProperty("db.password", ""));

        // 生成配置
        config.setAuthor(getProperty("gen.author", "admin"));
        config.setPackageName(getProperty("gen.packageName", "com.starry.play"));
        config.setOutputDir(getProperty("gen.outputDir", "./generated-code"));
        config.setAutoRemovePre(Boolean.parseBoolean(getProperty("gen.autoRemovePre", "false")));
        config.setTablePrefix(getProperty("gen.tablePrefix", "sys_"));
        config.setTplCategory(getProperty("gen.tplCategory", "crud"));

        // 验证必需的配置
        if (config.getUrl().isEmpty()) {
            throw new IllegalArgumentException("数据库连接地址不能为空，请配置 db.url");
        }
        if (config.getUsername().isEmpty()) {
            throw new IllegalArgumentException("数据库用户名不能为空，请配置 db.username");
        }

        return config;
    }

    private static String getProperty(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }
}
