/*
 * 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.seatunnel.datasource.plugin.oracle.jdbc;

import org.apache.seatunnel.api.configuration.util.OptionRule;
import org.apache.seatunnel.datasource.plugin.api.DataSourceChannelExt;
import org.apache.seatunnel.datasource.plugin.api.DataSourcePluginException;
import org.apache.seatunnel.datasource.plugin.api.model.TableField;
import org.apache.seatunnel.datasource.plugin.api.utils.JdbcUtils;

import org.apache.commons.lang3.StringUtils;

import lombok.NonNull;

import java.sql.*;
import java.util.*;

import static com.google.common.base.Preconditions.checkNotNull;

public class OracleDataSourceChannel implements DataSourceChannelExt {
    List<String> typeList = Arrays.asList("varchar","varchar2", "char", "json");
    @Override
    public OptionRule getDataSourceOptions(@NonNull String pluginName) {
        return OracleDataSourceConfig.OPTION_RULE;
    }

    @Override
    public OptionRule getDatasourceMetadataFieldsByDataSourceName(@NonNull String pluginName) {
        return OracleDataSourceConfig.METADATA_RULE;
    }

    @Override
    public List<String> getTables(
            @NonNull String pluginName,
            Map<String, String> requestParams,
            String database,
            Map<String, String> option) {
        List<String> tableNames = new ArrayList<>();
        try (Connection connection = getConnection(requestParams);
                ResultSet resultSet =
                        connection
                                .getMetaData()
                                .getTables(database, null, null, new String[] {"TABLE"}); ) {
            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                if (StringUtils.isNotBlank(tableName)) {
                    tableNames.add(tableName);
                }
            }
            return tableNames;
        } catch (ClassNotFoundException | SQLException e) {
            throw new DataSourcePluginException("get table names failed", e);
        }
    }

    @Override
    public List<String> getDatabases(
            @NonNull String pluginName, @NonNull Map<String, String> requestParams) {
        List<String> dbNames = new ArrayList<>();
        try (Connection connection = getConnection(requestParams);
                PreparedStatement statement = connection.prepareStatement("SHOW DATABASES;");
                ResultSet re = statement.executeQuery()) {
            // filter system databases
            while (re.next()) {
                String dbName = re.getString("database");
                if (StringUtils.isNotBlank(dbName)
                        && !OracleDataSourceConfig.ORACLE_SYSTEM_DATABASES.contains(dbName)) {
                    dbNames.add(dbName);
                }
            }
            return dbNames;
        } catch (Exception ex) {
            throw new RuntimeException("get databases failed", ex);
        }
    }

    @Override
    public boolean checkDataSourceConnectivity(
            @NonNull String pluginName, @NonNull Map<String, String> requestParams) {
        try (Connection ignored = getConnection(requestParams)) {
            return true;
        } catch (Exception e) {
            throw new DataSourcePluginException("check jdbc connectivity failed", e);
        }
    }

    @Override
    public List<TableField> getTableFields(
            @NonNull String pluginName,
            @NonNull Map<String, String> requestParams,
            @NonNull String database,
            @NonNull String table) {
        List<TableField> tableFields = new ArrayList<>();
        try (Connection connection = getConnection(requestParams, database)) {
            DatabaseMetaData metaData = connection.getMetaData();
            String primaryKey = getPrimaryKey(metaData, database, table);


            String sql =
                    "SELECT\n" +
                            "\tt.TABLE_NAME,\n" +
                            "\tt.COLUMN_NAME,\n" +
                            "\tt.COMMENTS,\n" +
                            "\tt1.DATA_TYPE,\n" +
                            "\tt1.DATA_LENGTH VAR_LEN,\n" +
                            "\tt1.DATA_PRECISION LEN,\n" +
                            "\tDATA_SCALE ,\n" +
                            "\tCASE NULLABLE\n" +
                            "\tWHEN 'N' THEN\n" +
                            "\t\t'true'\n" +
                            "\tELSE\n" +
                            "\t\t'false'\n" +
                            "END  IS_NULLABLE\n" +
                            "\n" +
                            "FROM\n" +
                            "\tall_col_comments t\n" +
                            "\tINNER JOIN all_tab_cols t1 ON t1.TABLE_NAME = t.table_name \n" +
                            "\tAND t1.COLUMN_NAME = t.column_name \n" +
                            "WHERE " +
                            "\tt.table_name = '"+table+"'  and  t.OWNER='"+database+"'";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);


                while (resultSet.next()) {
                    TableField tableField = new TableField();
                    String columnName = resultSet.getString("COLUMN_NAME");
                    tableField.setPrimaryKey(false);
                    if (StringUtils.isNotBlank(primaryKey) && primaryKey.equals(columnName)) {
                        tableField.setPrimaryKey(true);
                    }

                    if (typeList.contains(tableField.getType().toLowerCase())) {
                        tableField.setLen(resultSet.getString("VAR_LEN"));
                    } else {
                        tableField.setLen(resultSet.getString("LEN"));
                        tableField.setScale(resultSet.getString("DATA_SCALE"));
                    }
                    tableField.setName(columnName);
                    tableField.setType(resultSet.getString("TYPE_NAME"));
                    tableField.setComment(resultSet.getString("REMARKS"));
                    Object nullable = resultSet.getObject("IS_NULLABLE");
                    tableField.setNullable(Boolean.TRUE.toString().equals(nullable.toString()));
                    tableFields.add(tableField);
                }

        } catch (ClassNotFoundException | SQLException e) {
            throw new DataSourcePluginException("get table fields failed", e);
        }
        return tableFields;
    }

    @Override
    public Map<String, List<TableField>> getTableFields(
            @NonNull String pluginName,
            @NonNull Map<String, String> requestParams,
            @NonNull String database,
            @NonNull List<String> tables) {
        return null;
    }

    private String getPrimaryKey(DatabaseMetaData metaData, String dbName, String tableName)
            throws SQLException {
        ResultSet primaryKeysInfo = metaData.getPrimaryKeys(dbName, "%", tableName);
        while (primaryKeysInfo.next()) {
            return primaryKeysInfo.getString("COLUMN_NAME");
        }
        return null;
    }

    private Connection getConnection(Map<String, String> requestParams)
            throws SQLException, ClassNotFoundException {
        return getConnection(requestParams, null);
    }

    private Connection getConnection(Map<String, String> requestParams, String databaseName)
            throws SQLException, ClassNotFoundException {
        checkNotNull(requestParams.get(OracleOptionRule.DRIVER.key()));
        checkNotNull(requestParams.get(OracleOptionRule.URL.key()), "Jdbc url cannot be null");
        String url =
                JdbcUtils.replaceDatabase(
                        requestParams.get(OracleOptionRule.URL.key()), databaseName);
        if (requestParams.containsKey(OracleOptionRule.USER.key())) {
            String username = requestParams.get(OracleOptionRule.USER.key());
            String password = requestParams.get(OracleOptionRule.PASSWORD.key());
            return DriverManager.getConnection(url, username, password);
        }
        return DriverManager.getConnection(url);
    }

    @Override
    public List<Map> getTableAlls(
            @NonNull String pluginName,
            Map<String, String> requestParams,
            String database,
            Map<String, String> options) {
        List<Map> tableNames = new ArrayList<>();
        try (Connection connection = getConnection(requestParams);
                ResultSet resultSet =
                        connection
                                .getMetaData()
                                .getTables(database, null, null, new String[] {"TABLE"})) {
            while (resultSet.next()) {
                Map tables = new HashMap();

                ResultSetMetaData metaData = resultSet.getMetaData();
                //  获取表列数
                int columnCount = metaData.getColumnCount();
                for (int i = 1; i <= columnCount; i++) {

                    String tableName = resultSet.getString("TABLE_NAME");
                    if (StringUtils.isNotBlank(tableName)) {
                        tables.put("TABLE_NAME", tableName);
                    }

                    String tableComment = resultSet.getString("TABLE_COMMENT");

                    if (StringUtils.isNotBlank(tableComment)) {
                        tables.put("TABLE_COMMENT", tableComment);
                    }
                    tables.put(metaData.getColumnName(i), resultSet.getObject(i));
                }
            }
            return tableNames;
        } catch (ClassNotFoundException | SQLException e) {
            throw new DataSourcePluginException("get table names failed", e);
        }
    }
}
