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

import org.apache.seatunnel.shade.com.typesafe.config.ConfigFactory;

import org.apache.seatunnel.api.configuration.util.OptionRule;
import org.apache.seatunnel.datasource.plugin.api.DataSourceChannel;
import org.apache.seatunnel.datasource.plugin.api.DataSourcePluginException;
import org.apache.seatunnel.datasource.plugin.api.model.TableField;
import org.apache.seatunnel.datasource.plugin.influxdb.client.InfluxdbsClient;

import org.apache.commons.lang3.StringUtils;

import org.influxdb.InfluxDB;
import org.influxdb.dto.Query;
import org.influxdb.dto.QueryResult;

import lombok.NonNull;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class InfluxdbDataSourceChannel implements DataSourceChannel {

    private static final String DATABASE = "default";

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

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

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

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

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

    @Override
    public List<String> getTables(
            @NonNull String pluginName,
            Map<String, String> requestParams,
            String database,
            Map<String, String> option) {

        try {
            InfluxDB instance =
                    InfluxdbsClient.createInstance(ConfigFactory.parseMap(requestParams));
            instance.setDatabase(database);
            QueryResult showMeasurements = instance.query(new Query("show measurements"));
            List<QueryResult.Result> results = showMeasurements.getResults();
            List<String> table = new ArrayList<>();
            for (QueryResult.Result result : results) {
                List<List<Object>> values = result.getSeries().get(0).getValues();
                for (List<Object> value : values) {
                    table.add(String.valueOf(value.get(0)));
                }
            }
            return table;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> getDatabases(
            @NonNull String pluginName, @NonNull Map<String, String> requestParams) {
        InfluxDB instance = InfluxdbsClient.createInstance(ConfigFactory.parseMap(requestParams));
        boolean isConnected = false;
        QueryResult showDatabases = new QueryResult();
        try {
            // 尝试执行查询，如果成功，则连接成功
            showDatabases = instance.query(new Query("SHOW DATABASES"));
            isConnected = true;
        } catch (Exception e) {
            // 如果有异常，则连接失败
            e.printStackTrace();
        }
        List<QueryResult.Result> results = showDatabases.getResults();
        List<String> database = new ArrayList<>();
        for (QueryResult.Result result : results) {
            String name = result.getSeries().get(0).getName();
            database.add(name);
        }
        return database;
    }

    @Override
    public boolean checkDataSourceConnectivity(
            @NonNull String pluginName, @NonNull Map<String, String> requestParams) {
        try {

            InfluxDB instance =
                    InfluxdbsClient.createInstance(ConfigFactory.parseMap(requestParams));
            try {
                // 尝试执行查询，如果成功，则连接成功
                instance.query(new Query("SHOW DATABASES"));
                return true;
            } catch (Exception e) {
                // 如果有异常，则连接失败
                e.printStackTrace();
            }
            return false;
        } catch (Throwable e) {
            throw new DataSourcePluginException(
                    "check  InfluxDB connectivity failed, " + e.getMessage(), e);
        }
    }

    @Override
    public List<TableField> getTableFields(
            @NonNull String pluginName,
            @NonNull Map<String, String> requestParams,
            String database,
            String table) {
        // databaseCheck(database);
        try {
            InfluxDB instance =
                    InfluxdbsClient.createInstance(ConfigFactory.parseMap(requestParams));
            instance.setDatabase(database);
            QueryResult showDatabases = new QueryResult();
            try {
                // 尝试执行查询，如果成功，则连接成功
                showDatabases = instance.query(new Query("select * from " + table, database));
            } catch (Exception e) {
                // 如果有异常，则连接失败
                e.printStackTrace();
            }
            List<QueryResult.Result> results = showDatabases.getResults();
            List<TableField> fields = new ArrayList<>();
            for (QueryResult.Result result : results) {
                List<String> columns = result.getSeries().get(0).getColumns();
                for (String column : columns) {
                    TableField tableField = new TableField();
                    tableField.setName(column);
                    fields.add(tableField);
                }
            }
            return fields;
        } catch (Exception ex) {
            throw new DataSourcePluginException("Get table fields failed", ex);
        }
    }

    @Override
    public Map<String, List<TableField>> getTableFields(
            @NonNull String pluginName,
            @NonNull Map<String, String> requestParams,
            String database,
            List<String> tables) {
        InfluxDB instance = InfluxdbsClient.createInstance(ConfigFactory.parseMap(requestParams));
        instance.setDatabase(database);
        Map<String, List<TableField>> tableFields = new LinkedHashMap<>();
        for (String table : tables) {
            QueryResult showDatabases = new QueryResult();
            try {
                // 尝试执行查询，如果成功，则连接成功
                showDatabases = instance.query(new Query("select * from " + table, database));
            } catch (Exception e) {
                // 如果有异常，则连接失败
                e.printStackTrace();
            }
            List<QueryResult.Result> results = showDatabases.getResults();
            List<TableField> fields = new ArrayList<>();
            for (QueryResult.Result result : results) {
                List<String> columns = result.getSeries().get(0).getColumns();
                for (String column : columns) {
                    TableField tableField = new TableField();
                    tableField.setName(column);
                    fields.add(tableField);
                }
            }
            tableFields.put(table, fields);
        }
        return tableFields;
    }

    private static void databaseCheck(@NonNull String database) {
        if (!StringUtils.equalsIgnoreCase(database, DATABASE)) {
            throw new IllegalArgumentException("database not found: " + database);
        }
    }

    private TableField convertToTableField(String fieldName, String fieldType) {
        TableField tableField = new TableField();
        tableField.setName(fieldName);
        tableField.setType(fieldType);
        tableField.setComment(null);
        tableField.setNullable(true);
        tableField.setPrimaryKey(fieldName.equals("_id"));
        tableField.setDefaultValue(null);
        return tableField;
    }
}
