package cn.reghao.tnb.sb.db.autobatis.table;

import java.util.List;

/**
 * @author reghao
 * @date 2020-04-03 09:22:13
 */
public class SqlGenerator {
    public String copyTableSql(String srcTable, String destTable) {
        String sql = String.format("create table %s like %s", destTable, srcTable);
        return sql;
    }

    public String createSql(Table table) {
        String tableName = table.getName();
        String sqlSnippets = assembleSql(table.getTableFields());

        String line1 = "CREATE TABLE `" + tableName + "`  (\n";
        String line2 = "`id` int NOT NULL AUTO_INCREMENT,\n";
        //String line3 = "`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,\n";
        String line4 = "PRIMARY KEY (`id`) USING BTREE\n";
        String end = ") ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;\n";

        String uniqueLine;
        if (table.getUniqueKey() != null) {
            uniqueLine = "UNIQUE KEY (`" + table.getUniqueKey() + "`) USING BTREE,\n";
            //return line1 + line2 + sqlSnippets + line3 + uniqueLine + line4 + end;
            return line1 + line2 + sqlSnippets + uniqueLine + line4 + end;
        } else {
            //return line1 + line2 + sqlSnippets + line3 + line4 + end;
            return line1 + line2 + sqlSnippets + line4 + end;
        }
    }

    private String assembleSql(List<TableField> tableFields) {
        // 所有字段都是 NOT NULL，且不指定默认值
        String unsignedNumeric = "`{FIELD}` {TYPE} UNSIGNED NOT NULL DEFAULT 0,\n";
        String numeric = "`{FIELD}` {TYPE} NOT NULL DEFAULT 0,\n";
        String string = "`{FIELD}` {TYPE} NOT NULL DEFAULT \"\",\n";
        String timestamp = "`{FIELD}` {TYPE} NOT NULL DEFAULT CURRENT_TIMESTAMP,\n";

        StringBuilder sb = new StringBuilder();
        tableFields.forEach(field -> {
            String fieldName = field.getName();
            String fieldType = field.getSqlType();
            switch (field.getType()) {
                case numeric:
                    sb.append(numeric.replace("{FIELD}", fieldName).replace("{TYPE}", fieldType));
                    break;
                case unsigned_numeric:
                    sb.append(unsignedNumeric.replace("{FIELD}", fieldName).replace("{TYPE}", fieldType));
                    break;
                case string:
                    sb.append(string.replace("{FIELD}", fieldName).replace("{TYPE}", fieldType));
                    break;
                case timestamp:
                    sb.append(timestamp.replace("{FIELD}", fieldName).replace("{TYPE}", fieldType));
                    break;
                default:
            }
        });

        return sb.toString();
    }

    public String truncateSql(String table) {
        return "truncate table " + table;
    }

    public String dropSql(String table) {
        return "drop table " + table;
    }
}
