/*
 * 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.cdc.mysql;

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 com.google.common.collect.Sets;
import lombok.NonNull;

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

public class MysqlCDCDataSourceChannel implements DataSourceChannelExt {
    List<String> typeList = Arrays.asList("varchar", "char", "json");
    public static final Set<String> MYSQL_SYSTEM_DATABASES =
            Sets.newHashSet("information_schema", "mysql", "performance_schema", "sys");

    @Override
    public boolean canAbleGetSchema() {
        return true;
    }

    @Override
    public OptionRule getDataSourceOptions(@NonNull String pluginName) {
        return MysqlCDCOptionRule.optionRule();
    }

    @Override
    public OptionRule getDatasourceMetadataFieldsByDataSourceName(@NonNull String pluginName) {
        return MysqlCDCOptionRule.metadataRule();
    }

    @Override
    public List<String> getTables(
            String pluginName,
            Map<String, String> requestParams,
            String database,
            Map<String, String> option) {
        return this.getTableNames(requestParams, database);
    }

    @Override
    public List<String> getDatabases(String pluginName, Map<String, String> requestParams) {
        try {
            return this.getDataBaseNames(requestParams);
        } catch (SQLException e) {
            throw new DataSourcePluginException("get databases failed", e);
        }
    }

    @Override
    public boolean checkDataSourceConnectivity(
            String pluginName, Map<String, String> requestParams) {
        return this.checkJdbcConnectivity(requestParams);
    }

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

    @Override
    public Map<String, List<TableField>> getTableFields(
            String pluginName,
            Map<String, String> requestParams,
            String database,
            List<String> tables) {
        Map<String, List<TableField>> tableFields = new HashMap<>(tables.size());
        for (String table : tables) {
            tableFields.put(table, getTableFields(requestParams, database, table));
        }
        return tableFields;
    }

    @SuppressWarnings("checkstyle:MagicNumber")
    protected boolean checkJdbcConnectivity(Map<String, String> requestParams) {
        try (Connection connection = init(requestParams);
                Statement statement = connection.createStatement()) {

            try (ResultSet resultSet = statement.executeQuery("SHOW MASTER STATUS"); ) {
                if (resultSet.next()) {
                    String binlogFile = resultSet.getString("File");
                    if (StringUtils.isBlank(binlogFile)) {
                        throw new DataSourcePluginException("binlog must be enabled");
                    }
                } else {
                    throw new DataSourcePluginException("binlog must be enabled");
                }
            }

            try (ResultSet resultSet =
                    statement.executeQuery("SHOW VARIABLES LIKE 'binlog_format'")) {
                if (resultSet.next()) {
                    String binlogFormat = resultSet.getString("Value");
                    if (!"ROW".equalsIgnoreCase(binlogFormat)) {
                        throw new DataSourcePluginException("binlog_format must be ROW");
                    }
                } else {
                    throw new DataSourcePluginException("binlog_format must be ROW");
                }
            }

            try (ResultSet resultSet =
                    statement.executeQuery("SHOW VARIABLES LIKE 'binlog_row_image'")) {
                if (resultSet.next()) {
                    String binlogRowImage = resultSet.getString("Value");
                    if (!"FULL".equalsIgnoreCase(binlogRowImage)) {
                        throw new DataSourcePluginException("binlog_row_image must be FULL");
                    }
                } else {
                    throw new DataSourcePluginException("binlog_row_image must be FULL");
                }
            }
            return true;
        } catch (Exception e) {
            throw new DataSourcePluginException(
                    "check jdbc connectivity failed, " + e.getMessage(), e);
        }
    }

    protected Connection init(Map<String, String> requestParams) throws SQLException {
        if (null == requestParams.get(MysqlCDCOptionRule.BASE_URL.key())) {
            throw new DataSourcePluginException("Jdbc url is null");
        }
        String url = requestParams.get(MysqlCDCOptionRule.BASE_URL.key());
        if (null != requestParams.get(MysqlCDCOptionRule.PASSWORD.key())
                && null != requestParams.get(MysqlCDCOptionRule.USERNAME.key())) {
            String username = requestParams.get(MysqlCDCOptionRule.USERNAME.key());
            String password = requestParams.get(MysqlCDCOptionRule.PASSWORD.key());
            return DriverManager.getConnection(url, username, password);
        }
        return DriverManager.getConnection(url);
    }

    protected List<String> getDataBaseNames(Map<String, String> requestParams) throws SQLException {
        List<String> dbNames = new ArrayList<>();
        try (Connection connection = init(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) && isNotSystemDatabase(dbName)) {
                    dbNames.add(dbName);
                }
            }
            return dbNames;
        }
    }

    protected List<String> getTableNames(Map<String, String> requestParams, String dbName) {
        List<String> tableNames = new ArrayList<>();
        try (Connection connection = init(requestParams);
                ResultSet resultSet =
                        connection
                                .getMetaData()
                                .getTables(dbName, null, null, new String[] {"TABLE"})) {
            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                if (StringUtils.isNotBlank(tableName)) {
                    tableNames.add(tableName);
                }
            }
            return tableNames;
        } catch (SQLException e) {
            throw new DataSourcePluginException("get table names failed", e);
        }
    }

    protected List<TableField> getTableFields(
            Map<String, String> requestParams, String dbName, String tableName) {
        List<TableField> tableFields = new ArrayList<>();
        try (Connection connection = init(requestParams); ) {
            DatabaseMetaData metaData = connection.getMetaData();
            String primaryKey = getPrimaryKey(metaData, dbName, tableName);

            String sql =
                    "SELECT * FROM information_schema.COLUMNS "
                            + " WHERE "
                            + "TABLE_NAME = '"
                            + tableName
                            + "'  and  TABLE_SCHEMA='"
                            + dbName
                            + "'";
            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("DATA_TYPE"));
                if (typeList.contains(tableField.getType().toLowerCase())) {
                    if (tableField.getType().toLowerCase().indexOf("text") < 0) {
                        tableField.setLen(resultSet.getString("CHARACTER_MAXIMUM_LENGTH"));
                    }
                } else {
                    tableField.setLen(resultSet.getString("NUMERIC_PRECISION"));
                    tableField.setScale(resultSet.getString("NUMERIC_SCALE"));
                }

                tableField.setName(columnName);
                tableField.setComment(resultSet.getString("REMARKS"));
                tableField.setDefaultValue(resultSet.getString("COLUMN_DEFAULT"));
                Object nullable = resultSet.getObject("IS_NULLABLE");
                tableField.setNullable(Boolean.TRUE.toString().equals(nullable.toString()));
                tableFields.add(tableField);
            }
        } catch (SQLException e) {
            throw new DataSourcePluginException("get table fields failed", e);
        }
        return tableFields;
    }

    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 boolean isNotSystemDatabase(String dbName) {
        return MYSQL_SYSTEM_DATABASES.stream()
                .noneMatch(systemDatabase -> StringUtils.equalsIgnoreCase(systemDatabase, dbName));
    }

    private boolean convertToBoolean(Object value) {
        if (value instanceof Boolean) {
            return (Boolean) value;
        }
        if (value instanceof String) {
            return value.equals("TRUE");
        }
        return false;
    }

    @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 = init(requestParams)) {

            StringBuilder sql =
                    new StringBuilder("SELECT * 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();
            //            statement.execute("use " + database);
            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 (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 = init(requestParams); ) {
            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);
        }

        return null;
    }
}
