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

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

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

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

    @Override
    public OptionRule getDatasourceMetadataFieldsByDataSourceName(@NonNull String pluginName) {
        return null;
    }

    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 CAST(null AS VARCHAR(50)) AS TABLE_CAT,\n" +
                    "CAST(null AS VARCHAR(50)) AS TABLE_SCHEM,\n" +
                    "r.TABLE_NAME AS TABLE_NAME,\n" +
                    "l.TABLE_TYPE,\n" +
                    "l.REMARKS,\n" +
                    "l.TYPE_CAT,\n" +
                    "l.TYPE_SCHEM,\n" +
                    "l.TYPE_NAME,\n" +
                    "l.SELF_REFERENCING_COL_NAME,\n" +
                    "l.REF_GENERATION,\n" +
                    "l.HSQLDB_TYPE,\n" +
                    "l.READ_ONLY,\n" +
                    "l.COMMIT_ACTION \n" +
                    "FROM INFORMATION_SCHEMA.SYSTEM_TABLES l \n" +
                    "INNER JOIN UCA_METADATA.TABLES r  \n" +
                    "ON( l.TABLE_NAME= r.ESCAPED_TABLE_NAME)  \n" +
                    "WHERE \n" +
                    "TABLE_CAT = 'PUBLIC' AND TABLE_SCHEM = 'PUBLIC' AND TABLE_NAME  LIKE '%' ESCAPE '\\';";

            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<>();
        tableNames.add("all");
        return tableNames;

    }

    @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 INFORMATION_SCHEMA.SYSTEM_columns where TABLE_NAME='" + table.toUpperCase() + "' ";
            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);
                }
                tableField.setType(resultSet.getString("TYPE_NAME"));
                if (typeList.contains(tableField.getType().toLowerCase())) {
                    if (tableField.getType().toLowerCase().indexOf("text") < 0) {
                        tableField.setLen(resultSet.getString("COLUMN_SIZE"));
                    }
                } else {
                    tableField.setLen(resultSet.getString("COLUMN_SIZE"));
                    // tableField.setScale(resultSet.getString("SCALE"));
                }
                String extra = resultSet.getString("IS_AUTOINCREMENT");
                if (StringUtils.isNotBlank(extra) &&"YES".equals(extra.trim().toUpperCase())) {
                    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(org.apache.seatunnel.datasource.plugin.access.jdbc.AccessOptionRule.DRIVER.key()));
        checkNotNull(requestParams.get(org.apache.seatunnel.datasource.plugin.access.jdbc.AccessOptionRule.URL.key()), "Jdbc url cannot be null");
        String url =
                org.apache.seatunnel.datasource.plugin.access.jdbc.AccessOptionRule.URL.key();

        // 加载UCanAccess JDBC驱动
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        // 建立连接
        Connection conn = DriverManager.getConnection(url);
        System.out.println("Connected to the database successfully");
        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 CAST(null AS VARCHAR(50)) AS TABLE_CAT,\n" +
                    "CAST(null AS VARCHAR(50)) AS TABLE_SCHEM,\n" +
                    "r.TABLE_NAME AS TABLE_NAME,\n" +
                    "l.TABLE_TYPE,\n" +
                    "l.REMARKS,\n" +
                    "l.TYPE_CAT,\n" +
                    "l.TYPE_SCHEM,\n" +
                    "l.TYPE_NAME,\n" +
                    "l.SELF_REFERENCING_COL_NAME,\n" +
                    "l.REF_GENERATION,\n" +
                    "l.HSQLDB_TYPE,\n" +
                    "l.READ_ONLY,\n" +
                    "l.COMMIT_ACTION \n" +
                    "FROM INFORMATION_SCHEMA.SYSTEM_TABLES l \n" +
                    "INNER JOIN UCA_METADATA.TABLES r  \n" +
                    "ON( l.TABLE_NAME= r.ESCAPED_TABLE_NAME)  \n" +
                    "WHERE \n" +
                    "TABLE_CAT = 'PUBLIC' AND TABLE_SCHEM = 'PUBLIC' AND TABLE_NAME  LIKE '%' ESCAPE '\\';";
            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;
    }
}
