//----------------------------BEGIN LICENSE----------------------------
/* 
 * Willow : the Open Source WorkFlow Project
 * Distributable under GNU LGPL license by gun.org
 *
 * Copyright (C) 2004-2010 huihoo.org 
 * Copyright (C) 2004-2010  ZosaTapo <dertyang@hotmail.com> 
 * 
 * ====================================================================
 * Project Homepage : http://www.huihoo.org/willow
 * Source Forge     : http://sourceforge.net/projects/huihoo
 * Mailing list     : willow@lists.sourceforge.net 
 */
//----------------------------END  LICENSE-----------------------------
package org.huihoo.workflow.coreImpl.store;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.ConvertUtils;
import org.huihoo.commons.jdbc.JDBCFactory;
import org.huihoo.commons.jdbc.JDBCUtilities;
import org.huihoo.commons.jdbc.Store;
import org.huihoo.workflow.SchemaContext;
import org.huihoo.workflow.coreImpl.server.WorkflowCaseContextImpl;
import org.huihoo.workflow.server.WorkflowCase;
import org.huihoo.workflow.server.WorkflowCaseContext;
import org.huihoo.workflow.xpdl.WorkflowParameter;
import org.huihoo.workflow.xpdl.WorkflowProcess;
import org.huihoo.workflow.xpdl.util.TypeDefinition;

public class CaseContexUtilities
{
	public static WorkflowCaseContext createContext(
		Store storeConfig,
		SchemaContext schemaContext,
		WorkflowCase workflowCase)
		throws SQLException
	{
		WorkflowProcess workflowProcess = workflowCase.getWorkflowProcess();
		String processId = workflowProcess.getUUID();
		String packageId = workflowProcess.getWorkflowPackage().getUUID();
		String caseId = workflowCase.getUUID();

		List paramList = new ArrayList();
		WorkflowParameter parameter = null;

		String strSQL =
			"SELECT vc_uuid,vc_type,vc_value FROM "
				+ schemaContext.getTableName(SchemaContext.SCHEMA_CASE_DATAFIELD)
				+ " "
				+ "WHERE  vc_packageId=?"
				+ " "
				+ "AND    vc_processid=?"
				+ " "
				+ "AND    vc_caseId=?";

		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet jrs = null;

		try
		{
			conn = JDBCFactory.getConnection(storeConfig);
			pstmt = conn.prepareStatement(strSQL);
			pstmt.setString(1, packageId);
			pstmt.setString(2, processId);
			pstmt.setString(3, caseId);

			jrs = pstmt.executeQuery();

			String vc_uuid = null;
			String vc_type = null;
			String vc_value = null;

			while (jrs.next())
			{
				vc_uuid = jrs.getString("vc_uuid");
				vc_type = jrs.getString("vc_type");
				vc_value = jrs.getString("vc_value");

				parameter = new WorkflowParameter(vc_uuid, vc_uuid, TypeDefinition.XPDLToJava(vc_type));
				parameter.setValue(ConvertUtils.convert(vc_value, parameter.getType()));
				paramList.add(parameter);
			}

		}
		finally
		{
			JDBCUtilities.cleanupNoThrow(conn, pstmt);
		}

		return new WorkflowCaseContextImpl(workflowCase, paramList);
	}
}
