package com.beagle.informix.service.impl;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.beagle.informix.service.InformixService;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.Properties;




import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author lzz
 * date 2023/5/29
 * @version 1.0
 * description:
 */
@Slf4j
@Service("informixJdbcProxyService")
public class InformixJdbcProxyServiceImpl implements InformixService {



    public static void main(String[] args) {
        try {
            new InformixJdbcProxyServiceImpl().doConnectJob();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * informix.url=jdbc:informix-sqli://localhost:9088/sysadmin:INFORMIXSERVER=informix
     * informix.driverClassName=com.informix.jdbc.IfxDriver
     * informix.user=informix
     * informix.password=in4mix
     * 进入容器，使用dbaccess 进入informix
     * 问题： Invalid default sbspace name (sbspace).
     * 解决： onspaces -c -S sbspace -p /opt/ibm/data/spaces/sbspace.000 -o 100 -s 20000 -Df "LOGGING=ON"
     * @throws Exception
     */
    @Override
    public void doConnectJob() throws Exception{
        // todo 使用jdbc连接proxy，对应的query（clob、blob字段）存在jdbc 类型转换mysql异常的问题
        // Unknown exception: Can not find JDBC type `2005` in column type
        Driver driver =  getDriver();
        Connection conn = getConnection(driver);
        conn.prepareStatement("select * from \"test_tab_new24\"  ").execute();
        closeConnection(conn);
        deregisterDriver(driver);
    }
    private ResultSet getImportedKeys(Connection connection, DatabaseMetaData metaData, String tableName) throws SQLException {
        ResultSet schemas = connection.getMetaData().getSchemas();
        List<String> schemasList = new ArrayList<>();
        while (schemas.next()){
            schemasList.add(schemas.getString("TABLE_SCHEM"));
        }
        return connection.getMetaData().getImportedKeys((String)null, "BIT7", tableName);
    }



    private Object newForeignKey(ResultSet rs, String localTableName) throws SQLException {
        String localFieldName = this.parseStringValue(rs, "FKCOLUMN_NAME");
        String foreignFieldName = this.parseStringValue(rs, "PKCOLUMN_NAME");
        String foreignTableName = this.parseStringValue(rs, "PKTABLE_NAME");
        return null;
//        return new DatabaseMetaDataReaderImpl.ForeignKeyImpl(localTableName, localFieldName, foreignTableName, foreignFieldName);
    }

    private String parseStringValue(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        if (StringUtils.isBlank(value)) {
            return value;
        } else {
            Matcher m = STRING_VALUE.matcher(value);
            return m.find() ? m.group(1) : value;
        }
    }

    private static final Pattern STRING_VALUE = Pattern.compile("\"(.*)\"");


    private Driver getDriver() throws Exception{
        // 定义informix的驱动信息
//        String driverUrl = "com.mysql.jdbc.Driver";
        String driverUrl = "org.postgresql.Driver";
        // 还需要加入informix的jdbc驱动jar包
        Class<?> driverClass = Class.forName(driverUrl);
        return (Driver) driverClass.getConstructor().newInstance();
    }
    private void deregisterDriver(Driver driver) throws Exception{
        // 卸载驱动
        DriverManager.deregisterDriver(driver);
    }


    /**
     * 指定不用预编译语句 prepareThreshold=0
     * @param driver
     * @return
     * @throws Exception
     */
    private Connection getConnection(Driver driver) throws Exception{
        DriverManager.registerDriver(driver);
        Properties properties = new Properties();
        // 组装连接数据库信息 BITBUCKET_NEW
//        jdbc:informix-sqli://<server>:<port1526>/<database>:informixserver=<dbservername>
        StringBuilder jdbcBuilder = new StringBuilder("jdbc:postgresql://localhost:3307/testdb?character_set_results=utf8");// # ?useServerPrepStmts=true
        DriverManager.setLoginTimeout(10);
        properties.put("user", "root");
        properties.put("password", "Apurelove9014");
        return DriverManager.getConnection(jdbcBuilder.toString(), properties);
    }
    private void closeConnection(Connection connection) throws Exception {
        connection.close();
    }
}
