package com.leanwo.activiti.service.base.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.inject.Named;
import javax.sql.DataSource;

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

import com.leanwo.activiti.service.base.DbSyncTimeStampService;
import com.leanwo.activiti.util.SpringUtil;

@Named
public class DbSyncTimeStampServiceImpl implements DbSyncTimeStampService{
	private static Logger logger = LoggerFactory.getLogger(DbSyncTimeStampServiceImpl.class);
	
	
	@Override
	public void saveDbVersion(Long accountId, byte[] ufts) {
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		try {
			DataSource dataSource = SpringUtil.getBean("dataSource2");
			connection = dataSource.getConnection();
			preparedStatement = connection.prepareStatement("INSERT INTO ACT_ID_DbSyncTimeStamp VALUES(?, ?)");
			preparedStatement.setLong(1, accountId);
			preparedStatement.setBytes(2, ufts);
			preparedStatement.execute();
		} catch (SQLException e) {
			logger.error("新增dbTimeStamp失败");
			e.printStackTrace();
		}finally{
			try {
				if(connection != null){
					connection.close();
				}
				if(preparedStatement != null){
					preparedStatement.close();
				}
			} catch (SQLException e) {
				logger.error("数据库连接关闭失败");
				e.printStackTrace();
			}
		}
		
	}


	@Override
	public byte[] getLatestDbVersion(Long accountId) {
		byte[] ufts = new byte[8];
		Connection connection = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		try {
			DataSource dataSource = SpringUtil.getBean("dataSource2");
			connection = dataSource.getConnection();
			preparedStatement = connection.prepareStatement("SELECT dbTimeStamp FROM ACT_ID_DbSyncTimeStamp WHERE accountId = ? ORDER BY id");
			preparedStatement.setLong(1, accountId);
			resultSet = preparedStatement.executeQuery();
			while(resultSet.next()){
				ufts = resultSet.getBytes("dbTimeStamp");
			}
		} catch (SQLException e) {
			logger.error("查询dbTimeStamp失败");
			e.printStackTrace();
		}finally{
			try {
				if(connection != null){
					connection.close();
				}
				if(preparedStatement != null){
					preparedStatement.close();
				}
				if(resultSet != null){
					resultSet.close();
				}
			} catch (SQLException e) {
				logger.error("数据库连接关闭失败");
				e.printStackTrace();
			}
		}
		return ufts;
	}

}
