package com.fp.general.security.rules;

import com.fp.dto.rules.TransactionRule;
import com.fp.dto.save.SaveRequest;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pbpm.gene.TbpmGroupsUsers;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;
import com.fp.persistence.pgeneral.safe.TsafeUserDetailKey;
import com.fp.persistence.pgeneral.safe.TsafeUserSession;
import com.fp.persistence.pgeneral.safe.TsafeUserSessionKey;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;

/**
 * Clase que se va de encargar cuando se activa un usuario de eliminarlo de la tabla tsafeusersession para que se pueda loguear
 * @author scastillo
 */
public class MaintenanceUser extends TransactionRule {

    /**
     * Metodo que busca si estael usuario logueado lo eliminará de la sesion
     * @param sr
     * @return
     * @throws Exception 
     */
    @Override
    public SaveRequest normalProcess(SaveRequest sr) throws Exception {
        TsafeUserDetail tsafeUserDetail = (TsafeUserDetail) sr.getSaveBeanModifiedObject("TSAFEUSERDETAIL");
        if (tsafeUserDetail == null) {
        	tsafeUserDetail = (TsafeUserDetail) sr.getSaveBeanModifiedObject("USERDETAIL");
        }        
        if (tsafeUserDetail == null) {
            return sr;
        }
        String task = (String) tsafeUserDetail.get("task");
        String isuserbpm = tsafeUserDetail.getIsuserbpm();
        String usercode = tsafeUserDetail.getPk().getUsercode();
        TsafeUserDetailKey tsafeUserDetailKey = new TsafeUserDetailKey();
        tsafeUserDetailKey.setDateto(FormatDates.getDefaultExpiryTimestamp());
        tsafeUserDetailKey.setPersoncode(tsafeUserDetail.getPk().getPersoncode());
        tsafeUserDetailKey.setUsercode(tsafeUserDetail.getPk().getUsercode());
        TsafeUserDetail tsafeUserDetailPreview = TsafeUserDetail.find(PersistenceHelper.getEntityManager(), tsafeUserDetailKey);
        if (tsafeUserDetailPreview != null && tsafeUserDetailPreview.getUserstatuscatalog().compareTo("BLQ") == 0
                && tsafeUserDetail.getUserstatuscatalog().compareTo("ACT") == 0) {
//            TsafeUserSessionKey tsafeUserSessionKey = new TsafeUserSessionKey();
//            tsafeUserSessionKey.setDateto(FormatDates.getDefaultExpiryTimestamp());
//            tsafeUserSessionKey.setUsercode(tsafeUserDetail.getPk().getUsercode());
//            TsafeUserSession tsafeUserSession = TsafeUserSession.find(PersistenceHelper.getEntityManager(), tsafeUserSessionKey);
//            if (tsafeUserSession != null) {
//                Query qry = PersistenceHelper.getEntityManager().createQuery("update TsafeUserSession set pk.dateto=:expiration where pk.dateto = :dateto and pk.usercode = :usercode");
//                qry.setParameter("expiration", FormatDates.getInstance().getDataBaseTimestamp());
//                qry.setParameter("dateto", FormatDates.getDefaultExpiryTimestamp());
//                qry.setParameter("usercode", tsafeUserSession.getPk().getUsercode());
//                qry.executeUpdate();
//            }
        }
        this.verifyUserGroup(task, isuserbpm, usercode);
        return sr;
    }

    /**
     * Modo que se ejecuta en modo reverso
     * @param sr
     * @return
     * @throws Exception 
     */
    @Override
    public SaveRequest reverseProcess(SaveRequest sr) throws Exception {
        return sr;
    }

    /**
     * Verifica si el usuario del bpm a sido eliminado, lo elimina del grupo.
     * @param task
     * @param isuserbpm
     * @param usercode
     * @throws Exception 
     */
    private void verifyUserGroup(String task, String isuserbpm, String usercode) throws Exception {
        EntityManager em = PersistenceHelper.getEntityManager();

        if (task!=null && task.compareTo("NOTASK") == 0 && isuserbpm.compareTo("N") == 0) {
            Query qry = em.createQuery("from TbpmGroupsUsers g where g.pk.usercode = :code");
            qry.setParameter("code", usercode);
            @SuppressWarnings("unchecked")
            List<TbpmGroupsUsers> objs = (List<TbpmGroupsUsers>)qry.getResultList();
            if(!objs.isEmpty()){
                for(TbpmGroupsUsers tbpmGroupsUsers: objs){
                    PersistenceHelper.delete(tbpmGroupsUsers);
                }
            }
        }
    }
}
