// 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.doris.flink.sink;

import org.apache.doris.flink.cfg.DorisReadOptions;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.impl.NoConnectionReuseStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultRedirectStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.protocol.RequestContent;

import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;

import static org.apache.doris.flink.cfg.ConfigurationOptions.DORIS_REQUEST_CONNECT_TIMEOUT_MS_DEFAULT;
import static org.apache.doris.flink.cfg.ConfigurationOptions.SINK_HTTP_UTF8_CHARSET_DEFAULT;

/** util to build http client. */
public class HttpUtil {
    private final int connectTimeout;
    private final int waitForContinueTimeout;
    private final boolean httpUtf8Charset;
    private HttpClientBuilder httpClientBuilder;

    public HttpUtil() {
        this.connectTimeout = DORIS_REQUEST_CONNECT_TIMEOUT_MS_DEFAULT;
        this.waitForContinueTimeout = DORIS_REQUEST_CONNECT_TIMEOUT_MS_DEFAULT;
        this.httpUtf8Charset = SINK_HTTP_UTF8_CHARSET_DEFAULT;
        settingStreamHttpClientBuilder();
    }

    public HttpUtil(DorisReadOptions readOptions, boolean httpUtf8Charset) {
        this.connectTimeout = readOptions.getRequestConnectTimeoutMs();
        this.waitForContinueTimeout = readOptions.getRequestConnectTimeoutMs();
        this.httpUtf8Charset = httpUtf8Charset;
        settingStreamHttpClientBuilder();
    }

    private void settingStreamHttpClientBuilder() {
        ConnectionConfig connectionConfig = ConnectionConfig.DEFAULT;
        if (httpUtf8Charset) {
            connectionConfig =
                    ConnectionConfig.custom()
                            .setCharset(StandardCharsets.UTF_8)
                            .setMalformedInputAction(CodingErrorAction.REPLACE)
                            .setUnmappableInputAction(CodingErrorAction.REPLACE)
                            .build();
        }
        this.httpClientBuilder =
                HttpClients.custom()
                        .setDefaultConnectionConfig(connectionConfig)
                        // default timeout 3s, maybe report 307 error when fe busy
                        .setRequestExecutor(new HttpRequestExecutor(waitForContinueTimeout))
                        .setRedirectStrategy(
                                new DefaultRedirectStrategy() {
                                    @Override
                                    protected boolean isRedirectable(String method) {
                                        return true;
                                    }
                                })
                        .setRetryHandler((exception, executionCount, context) -> false)
                        .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
                        .setDefaultRequestConfig(
                                RequestConfig.custom()
                                        .setConnectTimeout(connectTimeout)
                                        .setConnectionRequestTimeout(connectTimeout)
                                        .build())
                        .addInterceptorLast(new RequestContent(true));
    }

    /**
     * for stream http
     *
     * @return
     */
    public CloseableHttpClient getHttpClient() {
        return httpClientBuilder.build();
    }

    /**
     * for batch http
     *
     * @return
     */
    public HttpClientBuilder getHttpClientBuilderForBatch() {
        ConnectionConfig connectionConfig = ConnectionConfig.DEFAULT;
        if (httpUtf8Charset) {
            connectionConfig =
                    ConnectionConfig.custom()
                            .setCharset(StandardCharsets.UTF_8)
                            .setMalformedInputAction(CodingErrorAction.REPLACE)
                            .setUnmappableInputAction(CodingErrorAction.REPLACE)
                            .build();
        }
        return HttpClients.custom()
                .setDefaultConnectionConfig(connectionConfig)
                .setRedirectStrategy(
                        new DefaultRedirectStrategy() {
                            @Override
                            protected boolean isRedirectable(String method) {
                                return true;
                            }
                        })
                .setDefaultRequestConfig(
                        RequestConfig.custom()
                                .setConnectTimeout(connectTimeout)
                                .setConnectionRequestTimeout(connectTimeout)
                                // todo: Need to be extracted to DorisExecutionOption
                                // default checkpoint timeout is 10min
                                .setSocketTimeout(9 * 60 * 1000)
                                .build());
    }

    public HttpClientBuilder getHttpClientBuilderForCopyBatch() {
        return HttpClients.custom()
                .disableRedirectHandling()
                .setDefaultRequestConfig(
                        RequestConfig.custom()
                                .setConnectTimeout(connectTimeout)
                                .setConnectionRequestTimeout(connectTimeout)
                                // todo: Need to be extracted to DorisExecutionOption
                                // default checkpoint timeout is 10min
                                .setSocketTimeout(9 * 60 * 1000)
                                .build());
    }
}
