package com.cmsz.dao;

import java.io.IOException;
import java.sql.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cmsz.ws.impl.UserServiceImpl;
import com.hp.cmsz.commons.utils.Constant;
import com.hp.cmsz.commons.utils.PropertiesUtil;

/**
 * 
 * @author huacha
 * 
 */

public class DAOSupport {
	private static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
	private Connection c;
	private PreparedStatement ps;
	private ResultSet rs = null;

	/**
	 * 
	 * @return
	 */
	protected Connection getConnection() throws SQLException {
		Connection conn = null;
		log.info("--Begin to get DB connection--");

		try {
			// DriverManager.registerDriver(new com.vertica.jdbc.Driver());
			String driver = PropertiesUtil.readValue(Constant.CONFIG_FILE,
					Constant.JDBC_DRIVER);
			log.info("driver is:" + driver);
			String url = PropertiesUtil.readValue(Constant.CONFIG_FILE,
					Constant.JDBC_URL);
			log.info("url is:" + url);
			String userName = PropertiesUtil.readValue(Constant.CONFIG_FILE,
					Constant.JDBC_USER_NAME);
			log.info("userName is:" + userName);
			String password = PropertiesUtil.readValue(Constant.CONFIG_FILE,
					Constant.JDBC_PASSWORD);
			log.info("password is:" + password);
			Class.forName(driver);
			conn = DriverManager.getConnection(url, userName, password);
			log.info("Get Connection successful");
			conn.setAutoCommit(false);
		} catch (IOException ie) {
			ie.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (conn);
	}

	/**
	 * 
	 * @param sql
	 * @return
	 */
	public ResultSet getResultSet(String sql) throws SQLException {
		if (c==null)
		{
		c = this.getConnection();
		}
		ps = c.prepareStatement(sql);
		rs = ps.executeQuery();
		return rs;
	}

	/**
	 * 
	 * @param sql
	 */
	public void executeSQL(String sql) throws SQLException {
		if (c==null)
		{
		c = this.getConnection();
		}
		ps = c.prepareStatement(sql);
		ps.executeUpdate();
	}

	public void commit() throws SQLException {
		if (c != null)

			c.commit();

	}

	public void rollback() throws SQLException {
		if (c != null)

			c.rollback();

	}

	/**
	 * 
	 * @param rs
	 */
	public void closeAll() throws SQLException

	{

		if (rs != null)
			rs.close();
		if (ps != null)
			ps.close();
		if (c != null)
			c.close();

	}

	public String checkEmptyString(String s) {
		if (s == null || s.isEmpty()) {
			return Constant.EMPTY_VALUE_FOR_4A;
		} else {
			return s;
		}
	}

	public Date checkEmptyDate(Date s) {
		if (s == null) {
			return (Date) (new java.util.Date());
		} else {
			return s;
		}
	}
}