package com.csc.library.utilities;

import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;

import com.csc.entity.CSC_Log;
import com.csc.library.database.DataSet;
import com.csc.library.database.FieldManager;
import com.csc.library.database.MyHashMap;
import com.csc.library.database.StaticProperties;
import com.csc.library.session.DbInquiry;
import com.csc.library.session.DbRecord;
import com.csc.library.session.InitialEnvironment;
import com.csc.library.session.InitialRecord;
public class UProfile extends HashMap {

	/**
	 * 
	 */
//	private static final long serialVersionUID = 3944654653762449118l;
	private static final long serialVersionUID = -7530940007418804146l;
	private CscCalendar startActive;
	private CscCalendar lastActive;
	private MyFont labelFont = new MyFont("label");
	private MyFont inputFont = new MyFont("input");
	private String myMessage = "";
	private String shortMessage = "";
	private String myStatus = "";
	private String LastMessage = "";
	private HashMap fieldConfigTemp = new HashMap();
	private CSC_Log oCSC_Log;
	private boolean log_info=MyLog.Info;
	private boolean log_debug=MyLog.Debug;
	private boolean log_warn=MyLog.Warning;
	private boolean log_production=MyLog.Production;
	private boolean log_display=MyLog.Display;
	private String processid="";
	private transient InitialEnvironment inv=new InitialEnvironment();

	public UProfile() {
		startActive = new CscCalendar();
		lastActive = new CscCalendar();		
		this.put("lang", "eng");
		this.put("appname", "");
		/**
		 * add by pas ���� ��� default �� ��͹�á����
		 * ���� employeeid =blank
		 * ���� companyid=100
		 */
		InitialEnvironment env=new InitialEnvironment("GLOBAL");
		String[] db =env.getValue("DBLIST-name").split(",");
		String dbName=db[0];
		this.put("dbname", dbName);
		this.put("employeeid", "");
		this.put("companyid", "100");
	}
	
	public UProfile(boolean c) {
		startActive = new CscCalendar();
		lastActive = new CscCalendar();		
		this.put("lang", "eng");
		this.put("appname", "");
	}
	
	public void initCSC_Log() {
		this.oCSC_Log = (CSC_Log) new InitialRecord(this).getDbRecord("com.csc.entity.CSC_Log");
	}
	
	public MyFont getLabelFont() {
		//return this.labelFont;
		return labelFont;
	}
	public MyFont getInputFont() {
		//return this.inputFont;
		return inputFont;
	}

	public void setDbName(String databaseName) {
		this.put("dbname", databaseName);
	}
	public String getDbName() {
		return (String) this.get("dbname");
	}

	public void setSchemaName(String schemaName) {
		this.put("schemaname", schemaName);
	}
	public String getSchemaName() {
		return (String) this.get("schemaname");
	}

	public void setUserId(String userId) {
		this.put("userid", userId);
	}
	public String getUserId() {
		return (String) this.get("userid");
	}

	public void setFullName(String fullname) {
		this.put("fullname", fullname);
	}
	public String getFullName() {
		return (String) this.get("fullname");
	}

	public void setEmployee(String employee) {
		this.put("employee", employee);
	}
	public String getEmployee() {
		return (String) this.get("employeeid");
	}

	public void setPassword(String password) {
		this.put("password", password);
	}
	public String getPassword() {
		return (String) this.get("password");
	}

	public void setUserName(String user) {
		this.put("user", user);
	}
	public String getUserName() {
		return (String) this.get("user");
	}

	public void setComCode(String comCode) {
		this.put("comcode", comCode);
	}
	public String getComCode() {
		return (String) this.get("comcode");
	}
	
	public String getCompanyid() {
		return (String) this.get("companyid");
	}

	public void setGroup(String group) {
		this.put("group", group);
	}
	public String getGroup() {
		return (String) this.get("group");
	}

	public void setLevel(String level) {
		this.put("level", level);
	}
	public String getLevel() {
		return (String) this.get("level");
	}

	public void setLastActive() {
		this.lastActive = new CscCalendar();
	}
	public CscCalendar getLastActive() {
		//return this.lastActive;
		return lastActive;
	}
	public CscCalendar getStartActive() {
		return this.startActive;
	}

	public void setStartActive() {
		this.startActive = new CscCalendar();
	}

	public void setActor(String actor) {
		this.put("actor", actor);
	}
	public boolean changeActor() {
		return (!this.getEmployee().equals(this.getActor()));
	}
	public String getActor() {
		return (String) this.get("actor");
	}
	public void setFullNameActor(String FNActor) {
		this.put("fullnameactor", FNActor);
	}

	public String getFullNameActor() {
		return (String) this.get("fullnameactor");
	}
	public String getCompanyName() {
		return (String) this.get("companyname");
	}

	public void setCompanyName(String companyName) {
		this.put("companyname", companyName);
	}
	public void setLocation(String pwlocation) {
		this.put("pwlocation", pwlocation);
	}

	public String getLocation() {
		return (String) this.get("pwlocation");
	}

	public void set(String name, String value) {
		this.put(name, value);
	}

	public String get(String name) {
		return (String) super.get(name);
	}
	
	public Object getObject(String name) {
		return (Object) super.get(name);
	}
	
	public HashMap getHashMap(String name) {
		return (HashMap) super.get(name);
	}
	
	public void setStartActive(CscCalendar startActive) {
		this.startActive = startActive;
	}
	public void setLastActive(CscCalendar lastActive) {
		this.lastActive = lastActive;
	}
	
	public void setFieldConfig(DbRecord db) throws RemoteException, Exception {
		MyHashMap hm = (MyHashMap) StaticProperties.FieldConfigTable;
		Vector myRelation=null;
		String fieldTarget, fieldSource;
		Vector listField = null;
		FieldManager fm=null;
		boolean ok=true;
		String columnList="";
		String sql="";
		String filter="";
		String dbData="";
		String tmp[]=null;
		DataSet ds=null;

		if (hm.containsKey(db.getTableName().toUpperCase())) {
				MyHashMap	myParent = (MyHashMap) hm.get(db.getTableName().toUpperCase());
				for(Iterator itParent = myParent.getKeyIterator(); itParent.hasNext();){
					String parentName =itParent.next().toString();
					myRelation = (Vector) myParent.get(parentName);				
					listField=(Vector)((MyHashMap)StaticProperties.systemField.get("fieldconfig")).get(parentName+"FL");
					parentName=parentName.substring(0,parentName.length()-7);
//					if (ds==null) {
						ds=new DataSet();
				        ds.setFetchAll(false);
						ds.setDbName(this.getDbName());
//					}
					columnList=listField.toString();
					columnList=columnList.replace("[","");
					columnList=columnList.replace("]","");
					sql="SELECT "+columnList+" FROM "+parentName; 
					filter="";
					for(int i = 0; i < myRelation.size(); i++) {
						tmp=myRelation.get(i).toString().split(",");
						fieldTarget = tmp[0];
						fieldSource = tmp[1];
						fm=db.getField(fieldTarget);
						if(fm!=null){
							filter+= fieldSource+"='"+fm.getString()+"'";
						}else{
							fm=db.getField(fieldSource);
							filter+= fieldTarget+"='"+fm.getString()+"'";
						}
						if(i<myRelation.size()-1)
							filter+=" and ";
					}
					if(filter.length()>0)
						sql+=" WHERE "+filter;
					try{
					ds.setSql(sql);
					ds.setTableName(parentName);
					ds.initConnection(this);
					ok=ds.next();
					if (ok) {
						for(int i = 0; i < listField.size(); i++) {
							fieldTarget = listField.get(i).toString();
							fm=db.getField(fieldTarget);
							dbData=ds.getString(fieldTarget);
							if(fm!=null){
								if(!db.getArrayFieldList().contains(fieldTarget.toLowerCase()))
									db.getArrayFieldList().add(fieldTarget.toLowerCase());
								fm.setEdit(false);
								fm.setWorking(true);
								fm.set(dbData);
							}
						}
					} else {
						MyLog.error(db, "Could not found parent record when config writing! "+parentName +" : "+sql);
						StaticProperties.myConnection.rollback(this, this);
					}
					}catch(Exception ex){
						
					}finally{
						ds.closeConnection();
					}
			}
		}
	}
	
	private boolean checkFieldConfigTemp(DbRecord db, DbInquiry dbInq, Vector relation)   throws RemoteException {
		boolean ok = true;
		String fieldTarget, fieldSource;
		String valueTarget, valueSource;
		for(int i = 0; i < relation.size() && ok; i++) {
			StringTokenizer sz = new StringTokenizer(relation.get(i).toString(), ",");
			fieldTarget = sz.nextToken();
			fieldSource = sz.nextToken();
			valueTarget = db.getString(fieldTarget);
			valueSource = dbInq.getString(fieldSource);
			if (!valueTarget.equals(valueSource)  ) ok = false;
		}
		return ok;
	}
	
	public void setMessage(String message) {
		this.myMessage		= message + this.myMessage;
		if (this.myMessage.length() > 4096) {
			this.myMessage = this.myMessage.substring(0, 2048);
		}
	}
	
	public void setMessage(String status, String message, String shortMessage) {
/*		
       setmessage ੾�� error ��� fatal ��ҹ��
        this.setSystemStatus(status);
		this.setMessage(message);
*/
		if (this.isErrorStatus(status)) {
			this.setSystemStatus(status);
			this.setMessage(message);
			this.shortMessage = shortMessage;
		}
	}
	
	public void setMessage(String status, String message) {
		if (!message.equals(this.LastMessage)) {
			this.setSystemStatus(status);
			this.setMessage(this.getDateTime()+": \r\n"+message);
		}
	}

	public void setSystemStatus(String status) {
		if (this.isErrorStatus(status)) {
			this.myStatus = status;
		}
	}
	
	public String getSystemStatus() {
		return this.myStatus;
	}
	
	public void clearSystemStatus(String status) {
		this.myStatus = "";
		this.myMessage = "";
		this.shortMessage="";
	}
	public String getMessage() {
		return this.myMessage; 
	}
	public String getShortMessage() {
		return this.shortMessage; 
	}
	public boolean isErrorStatus() {
		String fatal_error = "fe";
		if (!this.myStatus.equals("")) {
			if (fatal_error.indexOf(this.myStatus)>=0) {
				return true;
			}
		}
		return false;
	}
	
	public boolean isErrorStatus(String status) {
		String fatal_error = "fe";
		if (!status.equals("")) {
			if (fatal_error.indexOf(status)>=0) {
				return true;
			}
		}
		return false;
	}
	
	private String getDateTime() {
		CscCalendar d = new CscCalendar();
		return d.getDDMMYYYYHHMMSS();
	}
	
	public void clearFieldConfigTemp() {
		this.fieldConfigTemp = new HashMap();
	}
	
	public void setLogDebug(String flag){
		log_debug=Boolean.parseBoolean(flag);
	}
	public void setLogInFo(String flag){
		log_info=Boolean.parseBoolean(flag);
	}
	public void setLogWarn(String flag){
		log_warn=Boolean.parseBoolean(flag);
	}
	public void setLogProduction(String flag){
		log_production=Boolean.parseBoolean(flag);
	}
	public void setLogDisplay(String flag){
		log_display=Boolean.parseBoolean(flag);
	}
	
	public boolean getLogDebug(){
		return log_debug;
	}
	public boolean getLogInFo(){
		return log_info;
	}
	public boolean getLogWarning(){
		return log_warn;
	}
	public boolean getLogProduction(){
		return log_production;
	}
	public boolean getLogDisplay(){
		return log_display;
	}
	/* for Employee View */
	public String getEmvEmpId() {
		CheckNull chk = new CheckNull();
		return chk.chkNullString(this.get("emv_empid"), this.get("employeeid"));
	}
	public String getEmvName() {
		CheckNull chk = new CheckNull();
		if(!chk.chkNullString(this.get("emv_empid")).equals("")){
			return this.get("emv_fullname");
		}else{
			return this.get("fullname");
		}
	}
	public void setEmv(String subId, String subName) {
		this.setEmvEmpId(subId);
		this.setEmvName(subName);
	}
	public void setEmvEmpId(String subId) {
		this.put("emv_empid", subId);
	}
	public void setEmvName(String subName) {
		this.put("emv_fullname", subName);
	}	
	public String getDbType(){
		inv.setDbName(this.getDbName());
		return inv.getValue("datasource-dbtype");
	}
	
	public void setDefault(){
		this.setDbName(inv.getValue("db-name"));
		this.set("companyid", inv.getValue("db-companyid"));
		this.set("lang","tha");
	}

	public String getProcessid() {
		return processid;
	}

	public void setProcessid(String processid) {
		this.processid = processid;
	}

	public String getObjectID() {		
		return Integer.toHexString(System.identityHashCode(this));
	}
	
	public String getRandomString() {
		  Random rand=new Random();
		  int maxleng=3;
		  String str = "0123456789";
		  StringBuilder sb = new StringBuilder(maxleng);
		   for( int i = 0; i < maxleng; i++ ){
		      sb.append( str.charAt( rand.nextInt(str.length()) ) );
		   }		   
		   return sb.toString();
	}	

}