/*
 * 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.postgresql.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.commons.collections4.CollectionUtils;
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 PostgresqlDataSourceChannel implements DataSourceChannelExt {
    List<String> typeList = Arrays.asList("varchar", "char", "json");

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

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

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

    @Override
    public OptionRule getDatasourceMetadataFieldsByDataSourceName(@NonNull String pluginName) {
        return PostgresqlDataSourceConfig.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<>();
        String query = "SELECT table_schema, table_name FROM information_schema.tables";
        try (Connection connection = getConnection(requestParams, database)) {
            try (Statement statement = connection.createStatement();
                    ResultSet resultSet = statement.executeQuery(query)) {
                while (resultSet.next()) {
                    String schemaName = resultSet.getString("table_schema");
                    String tableName = resultSet.getString("table_name");
                    if (StringUtils.isNotBlank(schemaName)
                            && !PostgresqlDataSourceConfig.POSTGRESQL_SYSTEM_DATABASES.contains(
                                    schemaName)) {
                        tableNames.add(schemaName + "." + tableName);
                    }
                }
            }
            return tableNames;
        } catch (SQLException | ClassNotFoundException 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("select datname from pg_database;");
                ResultSet re = statement.executeQuery()) {
            while (re.next()) {
                String dbName = re.getString("datname");
                if (StringUtils.isNotBlank(dbName)
                        && !PostgresqlDataSourceConfig.POSTGRESQL_SYSTEM_DATABASES.contains(
                                dbName)) {
                    dbNames.add(dbName);
                }
            }
            return dbNames;
        } catch (SQLException | ClassNotFoundException e) {
            throw new DataSourcePluginException("get databases failed", e);
        }
    }

    @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[] split = table.split("\\.");
            if (split.length != 2) {
                throw new DataSourcePluginException(
                        "Postgresql tableName should composed by schemaName.tableName");
            }
            try (ResultSet resultSet = metaData.getColumns(database, split[0], split[1], null)) {
                getFileds(tableFields, primaryKey, resultSet);
            }
        } catch (SQLException | ClassNotFoundException e) {
            throw new DataSourcePluginException("get table fields failed", e);
        }
        return tableFields;
    }

    private static void getFileds(
            List<TableField> tableFields, String primaryKey, ResultSet resultSet)
            throws SQLException {
        while (resultSet.next()) {
            TableField tableField = new TableField();
            String nullable = resultSet.getString("IS_NULLABLE");
            if ("YES".equals(nullable.toUpperCase())) {
                tableField.setNullable(true);
            } else {
                tableField.setNullable(false);
            }

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

            String typeName = resultSet.getString("TYPE_NAME");
            System.out.println(typeName);
            tableField.setType(typeName);

            tableField.setName(columnName);
            String remarks = resultSet.getString("REMARKS");
            tableField.setComment(remarks);

            tableFields.add(tableField);
        }
    }

    @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(PostgresqlOptionRule.DRIVER.key()));
        checkNotNull(requestParams.get(PostgresqlOptionRule.URL.key()), "Jdbc url cannot be null");
        String url = requestParams.get(PostgresqlOptionRule.URL.key());
        String driver = requestParams.get(PostgresqlOptionRule.DRIVER.key());
        if (StringUtils.isEmpty(driver)) {
            driver = "org.postgresql.Driver";
        }
        Class Clazz = Class.forName(driver);
        Driver driverInstance = null;
        try {
            driverInstance = (Driver) Clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        DriverManager.registerDriver(driverInstance);

        if (requestParams.containsKey(PostgresqlOptionRule.USER.key())) {
            String username = requestParams.get(PostgresqlOptionRule.USER.key());
            String password = requestParams.get(PostgresqlOptionRule.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,
            String tableName,
            Map<String, String> options) {
        List<Map> tableNames = new ArrayList<>();
        try (Connection connection = getConnection(requestParams)) {
            StringBuilder sql =
                    new StringBuilder(
                            "SELECT table_schema, table_name  TABLE_NAME, table_comment TABLE_COMMENT  FROM information_schema.tables where 1=1 ");

            if (StringUtils.isNotBlank(database)) {

                sql.append(" and  table_schema='" + database + "'");
            }

            if (StringUtils.isNotBlank(tableName)) {

                sql.append(" and  table_name='" + tableName + "'");
            }
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql.toString());

            while (resultSet.next()) {
                Map tables = new HashMap();

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

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

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

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

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

        try (Connection connection = getConnection(requestParams, database)) {
            String sql =
                    "select * from information_schema.tables where table_name ='"
                            + tableName
                            + "' and table_schema ='"
                            + database
                            + "'";
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(sql);
            ResultSetMetaData metaData = resultSet.getMetaData();
            // 字段的个数
            int count = metaData.getColumnCount();
            // 创建List集合
            List<Map> list = new ArrayList<>();
            // 处理结果集
            while (resultSet.next()) {
                // 创建Map集合
                Map map = new HashMap<>();
                // 根据字段的个数, 循环
                for (int i = 0; i < count; i++) {
                    // 获取字段的名字
                    String columnName = metaData.getColumnName(i + 1);
                    // 获取字段对应的值
                    Object object = resultSet.getObject(columnName);
                    // 将字段名和字段值, 存入map集合中
                    map.put(columnName, object);
                }
                // 将map集合添加到List集合中
                list.add(map);
            }
            if (CollectionUtils.isNotEmpty(list)) {
                return list.get(0);
            }
        } catch (SQLException e) {
            throw new DataSourcePluginException("get table fields failed", e);
        } catch (ClassNotFoundException e) {
            throw new DataSourcePluginException("get table fields failed", e);
        }

        return null;
    }
}
