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

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
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 lombok.NonNull;


import java.net.URI;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class HttpDatasourceChannel implements DataSourceChannel {
    @Override
    public OptionRule getDataSourceOptions(@NonNull String pluginName) {
        return HttpOptionRule.optionRule();
    }

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

    @Override
    public boolean checkDataSourceConnectivity(
            @NonNull String pluginName, @NonNull Map<String, String> requestParams) {
        HttpConfiguration conf = HttpAConfiguration.getConfiguration(requestParams);
        try {
            HttpClient httpClient = HttpClientService.connect(conf);

            if (Objects.isNull(conf)) {
                throw new DataSourcePluginException(
                        String.format(
                                "check ftp connectivity failed, config is: %s", requestParams));
            }
            String url = conf.getUrl();
            String method = conf.getMethod();
            String token = conf.getToken();
            String parmams = conf.getRequest_params();
            // 目标URL
            URI uri = new URI(url);
            HttpResponse response = null;
            if (StringUtils.isBlank(method) || "GET".equals(method.toUpperCase())) {
                if (StringUtils.isNotBlank(parmams)) {
                    url = url + "?" + parmams;
                }
                System.out.println("url:" + url);
                HttpGet httpGet = new HttpGet(url);
                if (StringUtils.isNotBlank(token)) {
                    httpGet.setHeader("Authorization", "Bearer " + token.replace("Bearer ", "").trim());
                }

                // 执行请求并获得响应
                response = httpClient.execute(httpGet);
            } else if (StringUtils.isBlank(method) || "POST".equals(method.toUpperCase())) {
                HttpPost httpPost = new HttpPost(url);
                if (StringUtils.isNotBlank(token)) {
                    httpPost.setHeader("Authorization", "Bearer " + token.replace("Bearer ", "").trim());
                }
                // 设置请求体（例如：JSON数据）
                StringEntity requestEntity = new StringEntity(parmams);
                httpPost.setEntity(requestEntity);
                // 执行请求并获得响应
                response = httpClient.execute(httpPost);

            } else if (StringUtils.isBlank(method) || "PUT".equals(method.toUpperCase())) {
                HttpPut httpPut = new HttpPut(url);
                if (StringUtils.isNotBlank(token)) {
                    httpPut.setHeader("Authorization", "Bearer " + token.replace("Bearer ", "").trim());
                }
                // 设置请求体（例如：JSON数据）
                StringEntity requestEntity = new StringEntity(parmams);
                httpPut.setEntity(requestEntity);
                // 执行请求并获得响应
                response = httpClient.execute(httpPut);

            } else if (StringUtils.isBlank(method) || "DELETE".equals(method.toUpperCase())) {
                if (StringUtils.isNotBlank(parmams)) {
                    url = url + "?" + parmams;
                }
                System.out.println("url:" + url);
                HttpDelete httpDelete = new HttpDelete(url);

                if (StringUtils.isNotBlank(token)) {
                    httpDelete.setHeader("Authorization", "Bearer " + token.replace("Bearer ", "").trim());
                }

                // 执行请求并获得响应
                response = httpClient.execute(httpDelete);

            } else if (StringUtils.isBlank(method) || "PATCH".equals(method.toUpperCase())) {
                HttpPatch httpPatch = new HttpPatch(url);
                if (StringUtils.isNotBlank(token)) {
                    httpPatch.setHeader("Authorization", "Bearer " + token.replace("Bearer ", "").trim());
                }
                // 设置请求体（例如：JSON数据）
                StringEntity requestEntity = new StringEntity(parmams);
                httpPatch.setEntity(requestEntity);
                // 执行请求并获得响应
                response = httpClient.execute(httpPatch);

            } else if (StringUtils.isBlank(method) || "OPTIONS".equals(method.toUpperCase())) {
                if (StringUtils.isNotBlank(parmams)) {
                    url = url + "?" + parmams;
                }
                HttpOptions httpOptions = new HttpOptions(url);
                if (StringUtils.isNotBlank(token)) {
                    httpOptions.setHeader("Authorization", "Bearer " + token.replace("Bearer ", "").trim());
                }

                // 执行请求并获得响应
                response = httpClient.execute(httpOptions);

            } else if (StringUtils.isBlank(method) || "HEAD".equals(method.toUpperCase())) {
                if (StringUtils.isNotBlank(parmams)) {
                    url = url + "?" + parmams;
                }
                HttpHead httpHead = new HttpHead(url);
                if (StringUtils.isNotBlank(token)) {
                    httpHead.setHeader("Authorization", "Bearer " + token.replace("Bearer ", "").trim());
                }

                // 执行请求并获得响应
                response = httpClient.execute(httpHead);
            }

            int statusCode = response.getStatusLine().getStatusCode();
            // 打印响应状态
            System.out.println("Response Status: " + statusCode);

            // 获取响应内容
            String responseBody = EntityUtils.toString(response.getEntity());
            System.out.println("Response Body: " + responseBody);


            if (statusCode == 200) {
                return true;
            } else {
                throw new DataSourcePluginException(
                        String.format(
                                "check http connectivity failed, config is: %s", requestParams));
            }

        } catch (Exception e) {
            throw new DataSourcePluginException(
                    String.format("check http connectivity failed, config is: %s", requestParams));
        }
        //  return true;
    }

    @Override
    public List<String> getTables(
            @NonNull String pluginName,
            Map<String, String> requestParams,
            String database,
            Map<String, String> options) {
        throw new UnsupportedOperationException("getTables is not supported for Ftp datasource");
    }

    @Override
    public List<String> getDatabases(
            @NonNull String pluginName, @NonNull Map<String, String> requestParams) {
        throw new UnsupportedOperationException("getDatabases is not supported for Ftp datasource");
    }

    @Override
    public List<TableField> getTableFields(
            @NonNull String pluginName,
            @NonNull Map<String, String> requestParams,
            @NonNull String database,
            @NonNull String table) {
        throw new UnsupportedOperationException(
                "getTableFields is not supported for Ftp datasource");
    }

    @Override
    public Map<String, List<TableField>> getTableFields(
            @NonNull String pluginName,
            @NonNull Map<String, String> requestParams,
            @NonNull String database,
            @NonNull List<String> tables) {
        throw new UnsupportedOperationException(
                "getTableFields is not supported for Ftp datasource");
    }
}
