package com.tzy.config;

import com.impossibl.postgres.jdbc.PGConnectionPoolDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.sql.PooledConnection;
import java.sql.SQLException;

/**
 * @author by po'yi
 * @Classname CommonConfig
 * @Description TODO
 * @Date 2021/12/16 14:05
 */
//@Configuration
public class AppCommonConfig {

	@Value("${spring.datasource.druid.master.url}")
	private String dbUrl;
	@Value("${spring.datasource.druid.master.username}")
	private String username;
	@Value("${spring.datasource.druid.master.password}")
	private String password;

	//@Bean
	//public PGDataSource pgDataSource() {
	//	PGDataSource ds = new PGDataSource();
	//	//ds.setDatabaseUrl(dbUrl);
	//	ds.setHost("m2-dev.hobbystocks.cn");
	//	ds.setPort(5432);
	//	ds.setDatabaseName("tzy_system");
	//	ds.setUser(username);
	//	ds.setPassword(password);
	//	return ds;
	//}
	//
	@Bean
	public PooledConnection pooledConnection() throws SQLException {
		PGConnectionPoolDataSource source = new PGConnectionPoolDataSource();
		source.setServerName("m2-dev.hobbystocks.cn");
		source.setPortNumber(5432);
		source.setDatabaseName("tzy_system");
		source.setUser(username);
		source.setPassword(password);
		return source.getPooledConnection();
	}


	//@Bean
	//public void pgListen() throws SQLException {
	//    System.out.println("初始化监听器");
	//    //获取数据库连接
	//    Connection connection =pooledConnection().getConnection();
	//    //将数据库连接还原为原始的PGConnection
	//    PGConnection pgConnection = connection.unwrap(PGConnection.class);
	//    //为连接添加监听器
	//    pgConnection.addNotificationListener(new PGNotificationListener() {
	//        @Override
	//        public void notification(int processId, String channelName, String payload) {
	//            System.out.println("Received Notification: " + processId + ", " + channelName + ", " + payload);
	//        }
	//        @Override
	//        public void closed() {
	//            PGNotificationListener.super.closed();
	//        }
	//    });
	//
	//	//设置监听通道 对应pgnotify的channel
	//	Statement stmt = pgConnection.createStatement();
	//	stmt.executeUpdate("LISTEN CARD_GROUP_ORDER_INFO_MODIFIED_TEST");
	//	stmt.close();
	//}

	//@Bean
	//public ConnectionFactory connectionFactory(){
	//	ConnectionFactory connectionFactory= ConnectionFactories.get(ConnectionFactoryOptions.builder()
	//			.option(DRIVER,"postgresql")
	//			.option(HOST,host)
	//			.option(PORT,port)
	//			.option(USER,username)
	//			.option(PASSWORD,password)
	//			.option(DATABASE,database)
	//			.build());
	//
	//	ConnectionPoolConfiguration configuration = ConnectionPoolConfiguration.builder(connectionFactory)
	//			.maxIdleTime(Duration.ofMillis(1000))
	//			.maxSize(20)
	//			.build();
	//	// ConnectionPool实现了ConnectionFactory接口，使用ConnectionFactory替换ConnectionFactory
	//	return new ConnectionPool(configuration);
	//}
}
