package com.csc.library.database;
// files are imported exjava
// connectDB, DBTest, fieldAutonum, fieldDate, fieldTimestamp, myDB, myField
// myInquiry, myRecord, myRecordGroup, myReport, pwautonum, cscCalendar, myInquiry
// interface
// childmanager, fieldManager, tableManager, recordManager
// delete exjava classes
import java.io.Serializable;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;

import com.csc.library.session.InitialEnvironment;
import com.csc.library.session.keepLog;
import com.csc.library.utilities.ConvertHTML;
import com.csc.library.utilities.MyLog;
import com.csc.library.utilities.ThaiUtilities;
import com.csc.library.utilities.TransformSQL;
import com.csc.library.utilities.UProfile;

public class MyDB implements Serializable , keepLog{
	private String tableName="";
	protected String comp, user = "", pwd = "";
	private Hashtable compHash = new Hashtable();
	protected int stmtType = 0;
	protected boolean foundData = false;
	protected Connection inqCon1 = null;
	protected boolean autoCommit = false;
	protected ConnectManager connectCon = null;
	protected boolean requiredFound = false;
	protected boolean isChild = false;	
	protected java.sql.PreparedStatement stmt = null;
	protected UProfile userPro = new UProfile();
	protected RSecurityManager rm = null;
	protected String databaseName = "";
	protected String uid = "system";
//	private String dataSourceName = "";
	protected HashMap param = new HashMap();
	protected boolean isSave = true;

	protected boolean requireTransaction = false;
	//For Field Group
	protected HashMap groupField = new HashMap();
	protected String groupActive = "all";
	/***********ball edit 19-03-04**********/
	protected boolean referLang = false;
	/***********************/
    
    // add for RequireFound Follow Table
    protected Vector childRequire = null;
    
    protected String aliasname="";
    
    protected String dbtype="";
	protected String schemaName = "";    
    
    public void MyDB() {
		this.userPro.set("lang", "tha");
		this.userPro.setDbName(StaticProperties.serverManager.getDatabaseQuque());
		this.userPro.setUserName("Initial");
    }
    
	public void setParam(HashMap param) {
		this.param = param;
	}
	
	public void isSave(boolean issave){
		this.isSave=issave;
	} 
	
	public boolean isSave(){
		return this.isSave;
	} 
	
	public HashMap getParam() {
		return this.param;
	}
	public void setParam(String key, String value) {
		this.param.put(key, value);
	}
	public String getParam(String key) {
		return (String) this.param.get(key);
	}
	/**
	 * Modifiy by pas 
	 * chang String param to Vector
	 * @param gField
	 */
	public void setGroupfield(String gField) {
		this.groupActive = gField.toLowerCase();
		Class c = null;
		if (this instanceof MyInquiry) {
			c = MyInquiry.class;
		} else if (this instanceof MyRecord) {
			c = MyRecord.class;
		}else if(this instanceof MyTable){
			c = MyTable.class;
		}
		boolean type  =  true;
		
		if (this.groupActive.equalsIgnoreCase("all")) {
			type = true;
		} else {
			if (!this.groupField.containsKey(this.groupActive)) {
				type = true;
	        	MyLog.debug(this, "Can't not get FieldGroup >> " + this.groupActive);
			} else {
				type = false;
//				 gField = (Vector) this.groupField.get(this.groupActive);
			}
		}
		if (type) {

			try {
				String vcolumn = "*";
				Method m = c.getDeclaredMethod("setColumn", new Class[] { String.class });
				m.invoke(this, new Object[] { vcolumn });
			} catch (Exception e) {
	        	MyLog.error(this, this.userPro, e);
			}
			
		} else {
			Vector param = (Vector) this.groupField.get(this.groupActive);
			// if not have field group
			if (param == null) {
				param=new Vector();
				param.add("*");
	        	MyLog.debug(this, "Can't not get FieldGroup >> " + gField);
			}
			
			try {
				Method m = c.getDeclaredMethod("setColumn", new Class[] { Vector.class });
				m.invoke(this, new Object[] { param });
			} catch (Exception e) {
	        	MyLog.error(this, this.userPro, e);
			}
		}
	}
	public HashMap getGroupField() {
		return this.groupField;
	}
	public MyDB() {
	}
	protected int setTableDB(String table) {
		return 0;
	}
	public void setDataSource(String dataSourceName) {
//		this.dataSourceName = dataSourceName;
	}
	public void setPropDB(String comp, String user, String pwd) {
		this.comp = comp;
		this.user = user;
		this.pwd = pwd;
	}
	protected void initConnection() {
		if (this.inqCon1 == null) {
			//	this.inqCon1 = new ConnectDB(this.databaseName).getConnection();
		}
	}
	public Connection getUpdateConnection() {
		return null;
	}
	protected void getStatement(String statement) {
		try {
			stmt = this.inqCon1.prepareStatement(statement);
		} catch (SQLException sqlex) {
			MyLog.error(this, this.getUProfile(), sqlex);
		}
	}
	public String charCode(String point, String dataCon) {
		String convert = dataCon;
		ThaiUtilities thaicode = new ThaiUtilities();
		//convert=thaicode.ASCII2Unicode(dataCon);
		return convert;
	}
	public void setConnectControl(ConnectManager con) {
		this.connectCon = con;
	}
	public ConnectManager getConnectControl() {
		return this.connectCon;
	}
	public void setRequiredFound(boolean require) {
		this.requiredFound = require;
	}
	public boolean getRequiredFound() {
		return this.requiredFound;
	}
	public void release() {
		try {
			if (this.connectCon == null) {
				if (this.inqCon1 == null) {
					this.inqCon1.close();
				}
			} else {
				if (this.inqCon1 == null) {
					this.inqCon1.close();
				}
			}
		} catch (SQLException ex) {
			MyLog.error(this, this.getUProfile(), ex);
		}
	}
	/**
	 * set User Profile
	 * @param uPro  User Profile (User Detail)
	 */
	public void setUProfile(UProfile uPro) {
		this.userPro = uPro;
		this.databaseName = uPro.getDbName();
		this.schemaName = uPro.getSchemaName();
		this.dbtype = new InitialEnvironment(this.userPro.getDbName()).getValue("datasource-dbtype");

	}
	/**
	 * get User Profile
	 * @return UProfile
	 */
	public UProfile getUProfile() {
		return this.userPro;
	}
	/**
	 *  set Error Message
	 * @param mess
	 */
	public void setErrMess(String mess) {
	}
	/**
	 *  set Class Security for Record
	 * @param rm Record Security Manager
	 */
	public void setSecurity(RSecurityManager rm) {
		this.rm = rm;
	}
	public void isChild() {
		this.isChild = true;
	}

//	public void setTranSaction(javax.transaction.UserTransaction transaction) {
//		//this.transaction = transaction;
//		//this.requireTransaction = true;
//	}
//	protected void beginTransaction() {
//		if (this.requireTransaction) {
//			//this.logger.info(" BeginTransaction....");
//			try {
//				this.transaction.begin();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}
//	protected void commitTransaction() {
//		if (this.requireTransaction) {
//			//this.logger.info(" CommitTransaction....");
//			try {
//				this.transaction.commit();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}
//	/*
//	protected void commitTransaction(){
//			 	if(this.requireTransaction){
//					System.out.println(" CommitTransaction....");
//					try {
//						this.transaction.commit();	
//					} catch (Exception e) {
//						e.printStackTrace();
//					}		
//					
//			 	}
//		}
//	*/
//	protected void rollbackTransaction() {
//		if (this.requireTransaction) {
//			//this.logger.info(" RollbackTransaction....");
//			try {
//				this.transaction.rollback();
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//		}
//	}
	
	public RSecurityManager getSecurity(){
		return this.rm;
	}	

	protected String tfSql(String s) {
//		String dbtype = new InitialEnvironment(this.userPro.getDbName()).getValue("datasource-dbtype");
		String sr = new TransformSQL(this.getUProfile()).tfSql(this,s);
//		if (s != null) sr = new String(s);
//		if (dbtype != null && dbtype.equalsIgnoreCase("oracle")) {
//			while (sr.indexOf("''") > 0) {
//				int spindex = sr.indexOf("''");
//				if (sr.indexOf("=",spindex-4)>0) {
//					int opindex = sr.indexOf("=",spindex-4);
//					sr = sr.substring(0,opindex) + " is null" + sr.substring(spindex+2);
//				} else if (sr.indexOf("<>",spindex-4)>0) {
//					int opindex = sr.indexOf("<>",spindex-4);
//					sr = sr.substring(0,opindex) + " is not null" + sr.substring(spindex+2);
//				}
//			}
//			while (sr.indexOf("month(") > -1) {
//				int spindex = sr.indexOf("month(");
//				int lastopindex = sr.indexOf(")",spindex);
//				String data = sr.substring(spindex+6,lastopindex);
//				sr = sr.substring(0,spindex) + "to_char(" + data.trim() + ",'MM')" + sr.substring(lastopindex+1);
//			}
//			while (sr.indexOf("year(") > -1) {
//				int spindex = sr.indexOf("year(");
//				int lastopindex = sr.indexOf(")",spindex);
//				String data = sr.substring(spindex+6,lastopindex-1);
//				sr = sr.substring(0,spindex) + "to_char(" + data.trim() + ",'YYYY'))" + sr.substring(lastopindex+1);
//			}
//		}
		return sr;
	}
    
    /**
     *  Start RequireFound Table
     */
    public void setRequireFoundTable(String tablenames) {
        if (tablenames.trim().length() > 0) { 
            this.childRequire = new Vector();
        }
        StringTokenizer stn = new StringTokenizer(tablenames,",");
        while (stn.hasMoreTokens()) {
            String tablename = stn.nextToken();
            this.childRequire.add(tablename);
        }
    }
    
    public void setRequireFoundTable(Vector childRequire) {
        this.childRequire = childRequire;
    }
    
    public Vector getRequireFoundTable() {
        return this.childRequire;
    }
/**
 *  End RequireFound Table
 */
	public String getDataBaseName() {
		return this.databaseName;
	}
	public String getTableName() {
		return this.tableName;
	}
	
	public String getDataFormat(String fieldName){return "";}
			
	
	public String getStringHTML(String fieldName) {
		return ConvertHTML.convert(this.getDataFormat(fieldName));
	}

    public void setAliasName(String aliasname){
    	this.aliasname=aliasname;
    }
    public String getAliasName(){
    	return this.aliasname;
    }	
    
    public String getDbType(){
    	return this.dbtype;
    }
}