/**
 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
 * <p>
 * Licensed 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
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 io.jboot.db.driver;

import org.apache.http.impl.client.CloseableHttpClient;
import ru.yandex.clickhouse.ClickHouseConnectionImpl;
import ru.yandex.clickhouse.ClickhouseJdbcUrlParser;
import ru.yandex.clickhouse.settings.ClickHouseProperties;

import java.lang.reflect.Field;
import java.net.URISyntaxException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

public class OfficialClickHouseConnection extends ClickHouseConnectionImpl {


    private ClickHouseProperties properties;


    public OfficialClickHouseConnection(String url) throws SQLException {
        super(url);
        try {
            this.properties = ClickhouseJdbcUrlParser.parse(url,new Properties());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    }

    public OfficialClickHouseConnection(String url, ClickHouseProperties properties) throws SQLException {
        super(url, properties);
        try {
            this.properties = ClickhouseJdbcUrlParser.parse(url, properties.asProperties());
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(e);
        }
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
//      clickhouse 不支持 autoGeneratedKeys，但是 jfinal 调用了此方法会出错
        return prepareStatement(sql);
    }


   public void cleanConnections() {
       try {
           Field httpClientField = ClickHouseConnectionImpl.class.getDeclaredField("httpclient");
           httpClientField.setAccessible(true);
           CloseableHttpClient httpclient = (CloseableHttpClient) httpClientField.get(this);
           if (httpclient != null){
               httpclient.getConnectionManager().closeExpiredConnections();
               httpclient.getConnectionManager().closeIdleConnections(2 * properties.getSocketTimeout(), TimeUnit.MILLISECONDS);
           }
       } catch (NoSuchFieldException | IllegalAccessException e) {
           e.printStackTrace();
       }
    }


}
