package p2.util;

import java.sql.Connection;
import java.util.HashMap;

import p2.p2server.P2Server;
import p2.pao.PaoSetRemote;
import p2.security.ConnectionKey;

public class SetUniqueID {
	/*
	 * private long datamaxreserved; private long maxreserved; private long
	 * maxid;
	 */
	private String tablename;
	private String tableidname;

	public SetUniqueID(String tablename, String tableidname) throws P2Exception {
		this.tablename = tablename.toUpperCase();
		this.tableidname = tableidname.toUpperCase();
	}

	public SetUniqueID addNumbers(int addnumber) throws P2Exception {
		if (addnumber != 1) {
			PaoSetRemote tableset = P2Server.getP2Server().getPaoSet(tablename,
					P2Server.getP2Server().getSystemUserInfo());
			long maxid = (long) tableset.max(tableidname);// 当前表中的最大号
			tableset.close();

			PaoSetRemote PS_SEQUENCE = P2Server.getP2Server().getPaoSet(
					"PS_SEQUENCE", P2Server.getP2Server().getSystemUserInfo());
			PS_SEQUENCE.setWhere("tbname='" + this.tablename + "' and name='"
					+ tableidname + "'");
			PS_SEQUENCE.reset();
			if (!PS_SEQUENCE.isEmpty()) {
				PS_SEQUENCE.getPao(0).setValue("maxreserved",
						maxid + addnumber, 11L);
			}
			PS_SEQUENCE.save();
			PS_SEQUENCE.close();

			HashMap<String, p2.util.e> map = P2SequenceProvider.hm;
			map.remove(this.tablename + "_" + this.tableidname);
		}
		return this;
	}

	public long getUniqueIDValue() throws P2Exception {
		ConnectionKey locala= null;
		try {
			locala = P2Server.getP2Server().getSystemUserInfo()
					.getConnectionKey();
			Connection localConnection = P2Server.getP2Server()
					.getDBConnProvider().getConnection(locala);
			return p2.pao.m
					.a(localConnection, this.tablename, this.tableidname);
		} finally {
			P2Server.getP2Server().getDBConnProvider().freeConnection(locala);
		}
	}
	
}
