package net.wicp.tams.app.duckula.controller.service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.app.duckula.controller.bean.models.CommonCheckpoint;
import net.wicp.tams.app.duckula.controller.bean.models.busi.PositionBean;
import net.wicp.tams.app.duckula.controller.config.constant.CheckpointType;
import net.wicp.tams.common.Result;
import net.wicp.tams.common.apiext.jdbc.JdbcAssit;
import net.wicp.tams.common.binlog.alone.ListenerConf.Position;
import net.wicp.tams.common.jdbc.DruidAssit;

/**
 * 位点服务
 * 
 * @author Andy.zhou
 *
 */
@Service
@Slf4j
public class PosService {
	/**
	 * 查询位点
	 * 
	 * @param checkpointType
	 * @return
	 */
	public PositionBean selectPosition(CommonCheckpoint checkpoint, String taskName, Integer clientId) {
		if (checkpoint == null || clientId == null) {
			return null;
		}
		CheckpointType checkpointType = CheckpointType.valueOf(checkpoint.getCheckpointType());
		PositionBean retpos = null;
		switch (checkpointType) {
		case Memory:
		case H2db:
			break;
		case Mysql:
			retpos = selectMaxPositionByMysql(checkpoint, clientId);
			break;
		//case Zookeeper:
			// String taskNameTrue = CommandType.task.formateTaskName(taskName);
			// TODO
			//break;
		default:
			break;
		}
		return retpos;
	}

	/***
	 * mysql类型的
	 * 
	 * @param checkpoint
	 * @return
	 * @throws SQLException
	 */
	public List<PositionBean> selectPositionByMysql(CommonCheckpoint checkpoint, Integer clientId, Long lastTime,
			int maxSize,int interval) {
		DataSource dataSourceNoConf = getDataSource(checkpoint);
		List<PositionBean> retlist = new ArrayList<PositionBean>();
		try {
			PreparedStatement preStatement = dataSourceNoConf.getConnection().prepareStatement(
					"select * from position  where serverIp=? and clintId=? and time<=?   order by time desc limit 0,"
							+ (maxSize <= 0 ? 1 : maxSize));
			JdbcAssit.setPreParam(preStatement, checkpoint.getHost(), clientId, lastTime);
			ResultSet executeQuery = preStatement.executeQuery();
			long curtime=0;
			if (executeQuery.next()) {
				long time = executeQuery.getLong("time");
				if(time-curtime>=interval) {//大于指定的间隔时间
					PositionBean positionBean=new PositionBean();
					positionBean.setFileName(executeQuery.getString("fileName"));
					positionBean.setGtids(executeQuery.getString("gtids"));
					positionBean.setPos(executeQuery.getLong("pos"));
					positionBean.setMasterServerId(executeQuery.getLong("masterServerId"));
					positionBean.setTime(time);
					positionBean.setTimeStr(executeQuery.getString("timeStr"));
					positionBean.setServerIp(executeQuery.getString("serverIp"));
					positionBean.setClintId(executeQuery.getInt("clintId"));
					retlist.add(positionBean);
					curtime=time;
				}
			}
		} catch (SQLException e) {
			log.error("查询位点失败", e);
		}
		return retlist;
	}

	private DataSource getDataSource(CommonCheckpoint checkpoint) {
		Properties props = new Properties();
		props.put("host", checkpoint.getHost());
		props.put("port", checkpoint.getPort());
		props.put("defaultdb", checkpoint.getDefaultDb());
		props.put("username", checkpoint.getUsername());
		props.put("password", checkpoint.getPassword());
		DataSource dataSourceNoConf = DruidAssit.getDataSourceNoConf(checkpoint.getName(), props);
		return dataSourceNoConf;
	}
	
	public Result delPositionByMysql(CommonCheckpoint checkpoint, Integer clientId, Long lastTime) {
		DataSource dataSourceNoConf = getDataSource(checkpoint);
		try {
			PreparedStatement preStatement = dataSourceNoConf.getConnection().prepareStatement(
					"delete from position  where serverIp=? and clintId=? and time<=?");
			JdbcAssit.setPreParam(preStatement, checkpoint.getHost(), clientId, lastTime);
			preStatement.execute();
			return Result.getSuc();
		} catch (SQLException e) {
			log.error("刪除位点失败", e);
			return Result.getError(e.getMessage());
		}
	}
	
	

	public PositionBean selectMaxPositionByMysql(CommonCheckpoint checkpoint, Integer clientId) {
		List<PositionBean> selectList = selectPositionByMysql(checkpoint, clientId, Long.MAX_VALUE, 1,0);
		return CollectionUtils.isEmpty(selectList) ? null : selectList.get(0);
	}
	
	/**
	 * 
	 * @param checkpoint
	 * @param clientId
	 * @param second
	 * @return
	 */
	public List<PositionBean> selectPositionIntervalByMysql(CommonCheckpoint checkpoint, Integer clientId,int second) {
		List<PositionBean> selectList = selectPositionByMysql(checkpoint, clientId, Long.MAX_VALUE, 1,second*1000);
		return selectList;
	}
}
