package org.arefgard.container.orm;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.arefgard.container.aop.ClassGenerator;

/**
 * 
 * 
 * @author T.A.K.A.Dark
 */
public class Session {
	
	private Log log = LogFactory.getLog(Session.class);
	
	private Connection conn;
	
	private Map<String, String> mapping;
	
	public Session(Connection conn) {
		mapping = new java.util.HashMap<String, String>();
		this.conn = conn;
	}
	
	/**
	 * オブジェクト対テーブルのマッピングを設定する。
	 * 
	 * @param field
	 * @param type
	 * @param column
	 */
	public void addMapping(String field, String type, String column) {
		mapping.put(field, type + "," + column);
	}
	
	public Object find(String className, String table, String where) {
		PreparedStatement stmt = null;
		ResultSet result = null;
		Object ret = null;
		try {
			log.debug("select * from " + table + " where " + where);
			stmt = conn.prepareStatement("select * from " + table + " where " + where);
			result = stmt.executeQuery();
			
			Map<String, Object> property = new java.util.HashMap<String, Object>();
			while(result.next()) {
				Set<String> keys = this.mapping.keySet();
				
				for(Iterator<String> itr = keys.iterator(); itr.hasNext();) {
					String propName = itr.next();
					String value = mapping.get(propName);
					StringTokenizer token = new StringTokenizer(value, ",");
					String propType = token.nextToken();
					String propColumn = token.nextToken();
					log.debug(propName + "," + propType + "," + propColumn);
					if(propType.equals("string")) {
						property.put(propName, result.getString(propColumn));
					}
				}
			}
			ret = ClassGenerator.generate(className, property);
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				result.close();
				stmt.close();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
		return ret;
	}
	
	public void close() throws Exception {
		this.conn.close();
	}
}
