package baseclass.tools;

import p2.p2server.P2Server;
import p2.pao.PaoSetRemote;
import p2.util.P2Exception;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class GetFieldsName {
	String objectname;
	PaoSetRemote ps_objectcols;
	public static HashMap<String, String[]> objectcolsmap = new HashMap<String, String[]>(16);

	/**
	 * 构造函数
	 * 
	 * @param objectname
	 *            数据表名称
	 */
	public GetFieldsName(String objectname) throws P2Exception {
		this.objectname = objectname.toUpperCase();
		if (!objectcolsmap.containsKey(this.objectname)) {
			this.ps_objectcols = P2Server.getP2Server().getPaoSet("ps_objectcols",
					P2Server.getP2Server().getSystemUserInfo());
			ps_objectcols.setWhere("objectname='" + this.objectname
					+ "' and fieldname!='rmkenable' and fieldname!='recversion' and PERSISTENT=1");
			ps_objectcols.reset();
			int count = ps_objectcols.count();
            String[] allfields = new String[count];
			int i = 0;
			while (ps_objectcols.getPao(i) != null) {
				allfields[i] = ps_objectcols.getPao(i).getString("fieldname");
				i++;
			}
			objectcolsmap.put(this.objectname, allfields);
			ps_objectcols.close();
		}
	}

	/**
	 * 获取所有栏位名称
	 * 
	 * @return
	 * @throws P2Exception
	 */
	public String[] getFields() throws P2Exception {
		return objectcolsmap.get(objectname);
	}

	/**
	 * 获取除指定栏位外的栏位名称
	 * 
	 * @param exceptfields
	 *            需排除的栏位名称
	 * @return
	 * @throws P2Exception
	 */
	public String[] getFields(String[] exceptfields) throws P2Exception {
		StringBuilder a = new StringBuilder(objectname);
		for (String exceptfield : exceptfields) {
			a.append(exceptfield);
		}
		if (objectcolsmap.containsKey(a.toString())) {
			return objectcolsmap.get(a.toString());
		} else {
			List<String> exceptlist = Arrays.asList(exceptfields);
            String[] allfields = objectcolsmap.get(objectname);
			List<String> list = new ArrayList<String>();
			for (String field : allfields) {
				if (!exceptlist.contains(field)) {
					list.add(field);
				}
			}
			String[] s = list.toArray(new String[0]);
			objectcolsmap.put(a.toString(), s);
			return s;
		}

	}
}
