/*
 * Copyright (c) 2011-2021, baomidou (jobob@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package cn.stylefeng.team.meta.db.sdk.jdbc;

import cn.stylefeng.team.meta.api.pojo.db.DatabaseFieldDTO;
import org.apache.ibatis.type.JdbcType;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DatabaseMetaDataWrapper {

    private final DatabaseMetaData databaseMetaData;

    public DatabaseMetaDataWrapper(Connection connection) throws SQLException {
        this.databaseMetaData = connection.getMetaData();
    }

    public List<DatabaseFieldDTO> getFieldList(String catalog, String schemaPattern, String tableName) throws SQLException {

        List<String> keyColumnList = new ArrayList<>();
        ResultSet keyResultSet = databaseMetaData.getPrimaryKeys(catalog, schemaPattern, tableName);
        while (keyResultSet.next()) {
            String keyColumnName = keyResultSet.getString("COLUMN_NAME");//字段名称（英文）
            keyColumnList.add(keyColumnName);
        }

        ResultSet resultSet = databaseMetaData.getColumns(catalog, schemaPattern, tableName, "%");

        List<DatabaseFieldDTO> genDatabaseFieldDtoList = new ArrayList<>();
        while (resultSet.next()) {

            Map<String, Object> fieldMap = new HashMap<>();
            DatabaseFieldDTO genDatabaseFieldDto = new DatabaseFieldDTO();

            genDatabaseFieldDto.setFieldName(resultSet.getString("REMARKS"));

            String columnName = resultSet.getString("COLUMN_NAME");
            genDatabaseFieldDto.setFieldCode(columnName);

            genDatabaseFieldDto.setFieldType(JdbcType.forCode(resultSet.getInt("DATA_TYPE")).toString());

            genDatabaseFieldDto.setFieldLength(resultSet.getInt("COLUMN_SIZE"));

            genDatabaseFieldDto.setFieldDecimalPointLength(resultSet.getInt("DECIMAL_DIGITS"));

            String isNullable = resultSet.getString("IS_NULLABLE");

            if ("NO".equals(isNullable)) {
                genDatabaseFieldDto.setNotNullFlag("Y");
            } else if ("YES".equals(isNullable)) {
                genDatabaseFieldDto.setNotNullFlag("N");
            }

            if (keyColumnList.size() > 0) {
                for (String keyColumnName : keyColumnList) {
                    if (keyColumnName.equals(columnName)) {
                        genDatabaseFieldDto.setPrimaryKeyFlag("Y");
                    } else {
                        genDatabaseFieldDto.setPrimaryKeyFlag("N");
                    }
                }
            }
            genDatabaseFieldDtoList.add(genDatabaseFieldDto);
        }
        return genDatabaseFieldDtoList;
    }

}
