package com.beagle.informix.service.impl;


import com.beagle.informix.service.InformixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.Properties;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

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

    private ResourceLoader resourceLoader;

    public InformixJdbcProxyServiceImpl(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    public static void main(String[] args) {
        try {
            new InformixJdbcProxyServiceImpl(null).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{
        testAloneConnectionJob();
    }
    private void testSameConnectionJob(Connection connection) throws Exception{
        Driver driver =  getDriver();
        Connection conn = getConnection(driver);
        // 连接一直开启的话，发送的sql在proxy中都是使用一个同一个会话
        for (int i = 0; i < 100; i++) {
            String querySQL = "SELECT 1";
            Statement stat = connection.createStatement();
            ResultSet resultSet = stat.executeQuery(querySQL);
        }
        closeConnection(conn);
        deregisterDriver(driver);
    }

    private void testAloneConnectionJob() throws Exception{
        Driver driver =  getDriver();
        for (int i = 0; i < 100; i++) {
            // 这种情况下的话，每次新建一个连接，在proxy中都会对应新增一个连接
            Connection conn = getConnection(driver);
            String querySQL = "SELECT 1";
            Statement stat = conn.createStatement();
            ResultSet resultSet = stat.executeQuery(querySQL);
            closeConnection(conn);
        }
        deregisterDriver(driver);
    }

    private Driver getDriver() throws Exception{
        // 定义informix的驱动信息
        String driverUrl = "com.mysql.cj.jdbc.Driver";
        // 还需要加入informix的jdbc驱动jar包
        Class<?> driverClass = Class.forName(driverUrl);
        return (Driver) driverClass.getConstructor().newInstance();
    }
    private void deregisterDriver(Driver driver) throws Exception{
        // 卸载驱动
        DriverManager.deregisterDriver(driver);
    }
    private void insert(Connection conn) throws Exception{
        // 创建testdb数据库、my_test_create_table表
        // 现在模拟插入、更新、删除、查询等sql
        // 插入
        String insertSql = "insert  into  SYSDBA.cti_vccinfo_new (vccid ,vccname, effective, agentmax,ivrmax,updatekey,tclob,tblob) values (?, ? , ?, ?, ? , ?,?,? )";
        PreparedStatement stat = conn.prepareStatement(insertSql);
        stat.setObject(1, "123456");
        stat.setObject(2, "vname");
        stat.setObject(3, 1);
        stat.setObject(4, 2);
        stat.setObject(5, 3);
        stat.setObject(6, "updatekey");
        String clobContent = "This is a very very long string";
        // 处理clob字段
        StringReader reader = new StringReader(clobContent);
        stat.setClob(7, reader, clobContent.length());
        // 处理blob字段
        Resource resource = resourceLoader.getResource("classpath:EnableLoopback.exe");
        File inputStream = resource.getFile();
        FileInputStream fis = new FileInputStream(inputStream);
        stat.setBlob(8, fis);
        stat.executeUpdate();
    }
    private void update(Connection conn) throws Exception{
        // 创建testdb数据库、my_test_create_table表
        // 现在模拟插入、更新、删除、查询等sql
        // 插入
        String updateSql = "update  cti_vccinfo_new set vccname = 'informix_name' where vccid = '123456'";
        PreparedStatement stat = conn.prepareStatement(updateSql);
        stat.executeUpdate();
    }
    private void query(Connection conn) throws Exception {
        String querySQL = "SELECT id FROM sc_test";
        Statement stat = conn.createStatement();
        ResultSet resultSet = stat.executeQuery(querySQL);
    }



    private void delete(Connection conn) throws Exception{
        String deleteSql = "delete from cti_vccinfo_new where vccid = '123456' ";
        conn.createStatement().executeUpdate(deleteSql);
    }
    private Connection getConnection(Driver driver) throws Exception{
        DriverManager.registerDriver(driver);
        Properties properties = new Properties();
        // 组装连接数据库信息
//        jdbc:informix-sqli://<server>:<port1526>/<database>:informixserver=<dbservername>
        StringBuilder jdbcBuilder = new StringBuilder("jdbc:mysql://localhost:3307")
//                .append("/")
//                .append("SYSDBA");
                .append("?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai&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();
    }



}
