package com.mingsoft.jdbc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 建立数据库链接
 * 
 * @author 成卫雄 QQ:330216230 技术支持：景德镇铭飞科技 官网：www.ming-soft.com
 */
public class C3p0Connection {

	private static ComboPooledDataSource ds = new ComboPooledDataSource();// 直接使用即可，不用显示的配置，其会自动识别配置文件

	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); // map

	public static DataSource getDataSource() {
		return ds;
	}

	/**
	 * 重置c3p0配置文件,提供给安装过程使用
	 */
	public static void updateC3p0(String path) {
		try {

			Properties pro = new Properties();
			pro.load(new FileInputStream(new File(path)));
			ds.setJdbcUrl(pro.getProperty("c3p0.jdbcUrl"));
			ds.setPassword(pro.getProperty("c3p0.password"));
			ds.setUser(pro.getProperty("c3p0.user"));
			tl.remove();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection()  {
		try {
			// 得到当前线程上绑定的连接
			Connection conn = tl.get();
			if (conn == null ) { // 代表线程上没有绑定连接
				conn = ds.getConnection();
				tl.set(conn);
			}
			return conn;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
		}
	}

	public static Connection startTransaction() {
		Connection conn;
		try {
			// 得到当前线程上绑定连接开启事务
			conn = tl.get();
			
			if (conn == null) { // 代表线程上没有绑定连接
				conn = ds.getConnection();
				tl.set(conn);
			}
			conn.setAutoCommit(false);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return conn;
	}

	public static void commitTransaction() {
		try {
			Connection conn = tl.get();
			if (conn != null) {
				conn.commit();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static void closeConnection() {
		try {
			Connection conn = tl.get();
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			tl.remove(); // 千万注意，解除当前线程上绑定的链接（从threadlocal容器中移除对应当前线程的链接）
		}
	}

}
