/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 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 org.apache.kylin.source.jdbc.metadata;

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

import java.util.Locale;
import org.apache.kylin.source.hive.DBConnConf;
import org.apache.kylin.source.jdbc.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DefaultJdbcMetadata implements IJdbcMetadata {
    private final static Logger logger = LoggerFactory.getLogger(DefaultJdbcMetadata.class);
    protected DBConnConf dbconf;

    public DefaultJdbcMetadata(DBConnConf dbConnConf) {
        this.dbconf = dbConnConf;
    }

    @Override
    public List<String> listDatabases() throws SQLException {
        List<String> ret = new ArrayList<>();
        try (Connection con = SqlUtil.getConnection(dbconf); ResultSet rs = con.getMetaData().getSchemas()) {
            while (rs.next()) {
                String schema = rs.getString("TABLE_SCHEM");
                String catalog = rs.getString("TABLE_CATALOG");
                logger.info(String.format(Locale.ROOT, "%s,%s", schema, catalog));
                ret.add(schema);
            }
        }
        return ret;
    }

    @Override
    public List<String> listTables(String schema) throws SQLException {
        List<String> ret = new ArrayList<>();
        try (Connection con = SqlUtil.getConnection(dbconf);
                ResultSet rs = con.getMetaData().getTables(null, schema, null, null)) {
            while (rs.next()) {
                String name = rs.getString("TABLE_NAME");
                ret.add(name);
            }
        }
        return ret;
    }

    @Override
    public ResultSet getTable(final DatabaseMetaData dbmd, String schema, String table) throws SQLException {
        return dbmd.getTables(null, schema, table, null);
    }

    @Override
    public ResultSet listColumns(final DatabaseMetaData dbmd, String schema, String table) throws SQLException {
        return dbmd.getColumns(null, schema, table, null);
    }
}
