/*
*
* Sample program for use with the Product
* Licensed Materials  - Property of IBM
* 5724-I66
* (c) Copyright IBM Corp.  2006, 2009
*   
*/
package com.ibm.wbit.tel.client.jsf.query;

import static com.ibm.wbit.tel.client.jsf.infrastructure.SharedConstants.NLS_CATALOG;
import static com.ibm.wbit.tel.client.jsf.infrastructure.SharedConstants.QUERY_FAILED_BUSINESS_CASE_DETAILS;

import java.util.ArrayList;
import java.util.List;

import com.ibm.bpc.clientcore.ClientException;
import com.ibm.bpc.clientcore.GenericBPCQuery;
import com.ibm.bpe.api.PIID;
import com.ibm.task.api.QueryResultSet;
import com.ibm.task.clientmodel.HTMConnection;
import com.ibm.wbit.tel.client.jsf.bean.ToDoInstance;

/**
 * This class is to query the initiating originating task for
 * a given business process..
 */
public class BCGetTaskQuery extends GenericBPCQuery {

    /**
     * Connection to Human Task Manager to execute the query
     */
    private HTMConnection connection;

    /**
	 * Create a new instance.
	 * @param piid The process instance id for the process.
	 */
	public BCGetTaskQuery(final PIID piid) {
		super();
		setSelectClause("DISTINCT TASK.TKIID, TASK.ACTIVATED, TASK.NAME, TASK_TEMPL_DESC.DESCRIPTION, TASK.FIRST_ACTIVATED, TASK.COMPLETED, TASK.ORIGINATOR");
		setWhereClause("TASK.CONTAINMENT_CTX_ID=ID('" + piid + "') AND TASK.KIND=TASK.KIND.KIND_ORIGINATING");
		setOrderClause("TASK.FIRST_ACTIVATED");
		setThreshold(50);
		setType(ToDoInstance.class.getName());
	}

	/**
     * Executes the query against the <code>HumanTaskManagerService</code>.
     * The <code>HumanTaskManagerService</code> is determined by the connection property.
     * 
     * @see com.ibm.bpc.clientcore.Query#execute()
     * @throws ClientException: Any exception is caught,nested and rethrown as a <code>ClientException</code>
     */
    public List<ToDoInstance> execute() throws ClientException {
        final ArrayList<ToDoInstance> result = new ArrayList<ToDoInstance>(1);

        try {
            // Connect to the HTM API
            QueryResultSet apiResult = getConnection().getHumanTaskManagerService().query(getSelectClause(), getWhereClause(),
                    getOrderClause(), getThreshold(), null);

			// get the first row of the result set.
			apiResult.next();
			result.add(new ToDoInstance(apiResult, getConnection()));
        } catch (Exception e) {
            throw new ClientException(NLS_CATALOG, QUERY_FAILED_BUSINESS_CASE_DETAILS, null, e);
        }
        return result;
    }

    /**
     * @return Returns the connection.
     */
    public HTMConnection getConnection() {
        return connection;
    }

    /**
     * @param connection The connection to set.
     */
    public void setConnection(HTMConnection connection) {
        this.connection = connection;
    }
}