/*
 * 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.demeng.jdbc;

import org.apache.commons.collections4.CollectionUtils;
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 java.util.function.Function;
import java.util.stream.Collectors;

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

public class DemengJdbcDataSourceChannel implements DataSourceChannelExt {
    List<String> typeList = Arrays.asList("varchar", "char", "json");

    public static class Holder {
        private static final DemengJdbcDataSourceChannel INSTANCE = new DemengJdbcDataSourceChannel();
    }

    public static DemengJdbcDataSourceChannel getInstance() {
        return Holder.INSTANCE;
    }

    @Override
    public OptionRule getDataSourceOptions(@NonNull String pluginName) {
        return DemengDataSourceConfig.OPTION_RULE;
    }

    @Override
    public OptionRule getDatasourceMetadataFieldsByDataSourceName(@NonNull String pluginName) {
        return DemengDataSourceConfig.METADATA_RULE;
    }
    public static List<Map> getResultSet(ResultSet rs) throws SQLException {

        List<Map> reList=new ArrayList<>();
        ResultSetMetaData rsmd = rs.getMetaData() ;
        int columnCount = rsmd.getColumnCount();//ResultSet的总列数
        while (rs.next()) {
            Map map=new HashMap();
            for(int i=1;i<=columnCount;i++) {
                Object value = rs.getObject(i);
                String columnName = rsmd.getColumnName(i);
                map.put(columnName,value);

            }
            reList.add(map);

        }
        return reList;
    }

    @Override
    public List<String> getTables(
            @NonNull String pluginName,
            Map<String, String> requestParams,
            String database,
            Map<String, String> option) {
        List<String> tableNames = new ArrayList<>();
        // 定义 SQL 语句执行对象
        Statement state = null;
        // 定义结果集对象
        ResultSet rs = null;
        try (Connection connection = getConnection(requestParams)) {
            String sql_selectAll = "SELECT * FROM user_tables";
            if(StringUtils.isNotBlank(database)) {
                sql_selectAll=sql_selectAll+"  where TABLESPACE_NAME='" + database.toUpperCase() + "'";
            }
            state = connection.createStatement();
            //执行查询的 SQL 语句
            rs = state.executeQuery(sql_selectAll);
            List<Map> resultSet = getResultSet(rs);
            tableNames = resultSet.stream().filter(f -> f.get("TABLE_NAME") != null).map(m -> m.get("TABLE_NAME") + "").collect(Collectors.toList());
            return tableNames;
        } catch (ClassNotFoundException | SQLException e) {
            throw new DataSourcePluginException("get table names failed", e);
        }finally {
            try {
                //关闭资源
                rs.close();
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<String> getDatabases(
            @NonNull String pluginName, @NonNull Map<String, String> requestParams) {
        List<String> tableNames = new ArrayList<>();
        // 定义 SQL 语句执行对象
        Statement state = null;
        // 定义结果集对象
        ResultSet rs = null;
        try (Connection connection = getConnection(requestParams)) {
            String sql_selectAll = "SELECT TABLESPACE_NAME FROM user_tables group by TABLESPACE_NAME ";

            state = connection.createStatement();
            //执行查询的 SQL 语句
            rs = state.executeQuery(sql_selectAll);
            List<Map> resultSet = getResultSet(rs);
            tableNames = resultSet.stream().filter(f -> f.get("TABLESPACE_NAME") != null).map(m -> m.get("TABLESPACE_NAME") + "").collect(Collectors.toList());
            return tableNames;
        } catch (ClassNotFoundException | SQLException e) {
            throw new DataSourcePluginException("get Databases names failed", e);
        }finally {
            try {
                //关闭资源
                rs.close();
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @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 * from  SYSCOLUMNS where id in (select id from  SYSOBJECTS where name='"+table.toUpperCase()+"')";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
                TableField tableField = new TableField();
                String columnName = resultSet.getString("NAME");
                tableField.setPrimaryKey(false);
                if (StringUtils.isNotBlank(primaryKey) && primaryKey.equals(columnName)) {
                    tableField.setPrimaryKey(true);
                }
                tableField.setType(resultSet.getString("TYPE$"));
                if (typeList.contains(tableField.getType().toLowerCase())) {
                    if (tableField.getType().toLowerCase().indexOf("text") < 0) {
                        tableField.setLen(resultSet.getString("LENGTH$"));
                    }
                } else {
                    tableField.setLen(resultSet.getString("LENGTH$"));
                    tableField.setScale(resultSet.getString("SCALE"));
                }
                String extra = resultSet.getString("INFO2");
                if (StringUtils.isNotBlank(extra) && extra.trim().equals("1")) {
                    tableField.setHasAutoIncrement(true);
                }

                tableField.setName(columnName);
              //  tableField.setComment(resultSet.getString("COLUMN_COMMENT"));
              //  tableField.setDefaultValue(resultSet.getString("COLUMN_DEFAULT"));
                String nullable = resultSet.getString("NULLABLE$");

                if("Y".equals(nullable)) {
                    tableField.setNullable(true);
                } else {
                    tableField.setNullable(false);
                }

                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 tables.parallelStream()
                .collect(
                        Collectors.toMap(
                                Function.identity(),
                                table ->
                                        getTableFields(
                                                pluginName, requestParams, database, table)));
    }

    private String getPrimaryKey(DatabaseMetaData metaData, String dbName, String tableName)
            throws SQLException {
        ResultSet primaryKeysInfo = metaData.getPrimaryKeys(dbName, "%", tableName);
        while (primaryKeysInfo.next()) {
            return primaryKeysInfo.getString("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(DemengOptionRule.DRIVER.key()));
        checkNotNull(requestParams.get(DemengOptionRule.URL.key()), "Jdbc url cannot be null");
        String url =
                DemengOptionRule.URL.key();
        if (requestParams.containsKey(DemengOptionRule.USER.key())) {
            String username = requestParams.get(DemengOptionRule.USER.key());
            String password = requestParams.get(DemengOptionRule.PASSWORD.key());

            Class.forName(DemengOptionRule.DriverType.DEMENG.getDriverClassName());
            Connection   conn = DriverManager.getConnection(url, username, password);
            conn.setAutoCommit(true);
            return conn;
        }
        Class.forName(DemengOptionRule.DriverType.DEMENG.getDriverClassName());
        Connection   conn = DriverManager.getConnection(url, "SYSDBA", null);
        conn.setAutoCommit(true);
        return conn;
    }

    @Override
    public List<Map> getTableAlls(
            @NonNull String pluginName,
            Map<String, String> requestParams,
            String database,
            String tableName,
            Map<String, String> options) {

        // 定义 SQL 语句执行对象
        Statement state = null;
        // 定义结果集对象
        ResultSet rs = null;
        try (Connection connection = getConnection(requestParams)) {
            String sql_selectAll = "SELECT * FROM user_tables";
            if(StringUtils.isNotBlank(database)) {
                sql_selectAll=sql_selectAll+"  where TABLESPACE_NAME='" + database.toUpperCase() + "'";
            }
            state = connection.createStatement();
            //执行查询的 SQL 语句
            rs = state.executeQuery(sql_selectAll);
            List<Map> resultSet = getResultSet(rs);

            return resultSet;
        } catch (ClassNotFoundException | SQLException e) {
            throw new DataSourcePluginException("get table names failed", e);
        }finally {
            try {
                //关闭资源
                rs.close();
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public Map getTableName(
            @NonNull String pluginName,
            Map<String, String> requestParams,
            String database,
            Map<String, String> options,
            String tableName) {

        List<Map> list = getTableAlls(pluginName,requestParams,database,tableName,options);
        if (CollectionUtils.isNotEmpty(list)) {
                return list.get(0);
            }

        return null;
    }
}
