/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fp.bpmlib.query.groups;

import java.util.List;

import javax.persistence.EntityManager;

import com.fp.bpm.query.Query;
import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pbpm.gene.TbpmGroupsUsers;
import com.fp.persistence.pcustomer.gene.TcustPersonDetail;
import com.fp.persistence.pcustomer.gene.TcustPersonDetailKey;
import com.fp.persistence.pgeneral.safe.TsafeUser;

// TODO: Auto-generated Javadoc
/**
 * Class UserToGroup encargada de.
 * 
 * @author BPTWPA
 */
public class UserToGroup extends QueryRule {

    /** Constante serialVersionUID. */
    private static final long serialVersionUID = 1L;

    /**
     * Process.
     * 
     * @param pQueryRequest the query request
     * @return query request
     * @throws Exception la exception
     */
    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        EntityManager em = PersistenceHelper.getEntityManager();
        Response response = pQueryRequest.getResponse();
        Query qry = new Query();
        qry.process(pQueryRequest);
        @SuppressWarnings("unchecked")
        List<Object> lobjects = (List<Object>) response.get("TBPMGROUPSUSERS");
        if (!lobjects.isEmpty()) {
            for (Object obj : lobjects) {
                TbpmGroupsUsers tbpmGroupsUsers = (TbpmGroupsUsers) obj;
                if (tbpmGroupsUsers.getPk().getUsercode() != null) {
                    TsafeUser tsafeUser = TsafeUser.find(em, tbpmGroupsUsers.getPk().getUsercode());
                    if (tsafeUser != null) {
                        TcustPersonDetailKey custPersonDetailKey = new TcustPersonDetailKey(tsafeUser.getPersoncode(),
                                FormatDates.getDefaultExpiryTimestamp());
                        TcustPersonDetail tcutPersonDetail = TcustPersonDetail.find(em, custPersonDetailKey);
                        tbpmGroupsUsers.addAddtionalInfo("username", ((tcutPersonDetail == null) ? "" : tcutPersonDetail.getName()));
                    }
                }
            }
        }
        return pQueryRequest;
    }
}
