package com.fp.general.rules.query;

import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import org.hibernate.SQLQuery;
import org.hibernate.ScrollableResults;
import java.util.ArrayList;
import java.util.List;

/**
 * Clase que se encarga de ejecutar un query que se envía desde la parte web
 * @author scastillo
 */
public class ExecuteSQL extends QueryRule {

    /**
     *
     * @param pQueryRequest
     * @return
     * @throws Exception
     */
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        Response response = pQueryRequest.getResponse();
        String sql = (String) pQueryRequest.get("sql");
        String isUniqueResult = (String) pQueryRequest.get("isUniqueResult");
        SQLQuery qry = PersistenceHelper.getSession().createSQLQuery(sql);
        if (isUniqueResult.equals("Y")) {
            Object data = qry.uniqueResult();
            response.put("result", data);
        } else {
            ScrollableResults scrollableResults = qry.scroll();
            List<Object> lObject = new ArrayList<Object>();
            while (scrollableResults.next()) {
                lObject.add(scrollableResults.get());
            }
            response.put("result", lObject);
        }
        return pQueryRequest;
    }
}
