package com.fp.general.security.rules;

import javax.persistence.NoResultException;
import javax.persistence.Query;

import com.fp.dto.rules.TransactionRule;
import com.fp.dto.save.SaveRequest;
import com.fp.general.exception.GeneralException;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pgeneral.safe.TsafeUser;
import com.fp.persistence.pgeneral.safe.TsafeUserDetail;
import com.fp.sessionbeans.helper.Sequence;

/**
 * Clase que se encuentra del manejo
 * @author scastillo
 */
public class CreateInternalCodeUser extends TransactionRule {

	private static final long serialVersionUID = 1L;

	/**
     * Metodo que se encarga de completar el codigo interno eln la creacion de usuarios
     * @param pSaveRequest
     * @return
     * @throws Exception
     */
    public SaveRequest normalProcess(SaveRequest pSaveRequest) throws Exception {
    	// Si la pantalla es diferente de tx 1 120 , se procede a validar creacion de usuarios  	
    	if(!pSaveRequest.get("PANTALLA").toString().equalsIgnoreCase("USUARIOSPERFIL_MOD1_TX120")){    	
	    	if( !pSaveRequest.isJsf()){
	            TsafeUser tsafeUser = (TsafeUser) pSaveRequest.getSaveBeanModifiedObject("TSAFEUSER");
	            this.validateuser(tsafeUser.getPk().trim(), tsafeUser.getCompanycode());            
	            tsafeUser.setInternalcode(getInternalCode());    		
	    	}else{
	    		this.proessjsf(pSaveRequest);
	    	}
    	}
        return pSaveRequest;
    }
    
    private void proessjsf(SaveRequest pSaveRequest) throws Exception {
    	TsafeUserDetail ud = (TsafeUserDetail) pSaveRequest.getSaveBeanModifiedObject("USERDETAIL");
    	if(ud == null){
    		return;
    	}
    	this.validateuser(ud.getPk().getUsercode(), ud.getCompanycode());
    	TsafeUser tsu = new TsafeUser(ud.getPk().getUsercode());
    	tsu.setPersoncode(ud.getPk().getPersoncode());
    	tsu.setCompanycode(ud.getCompanycode());
    	tsu.setInternalcode(getInternalCode());
    	pSaveRequest.putSaveBean("TSAFEUSER", tsu, 1);
    }
    
    private void validateuser(String usercode, Integer company) throws Exception {
    	 String code = this.findUser(usercode, company);
        if(code!=null){
        	throw new GeneralException("GENE-0042", "CÓDIGO DE USUARIO YA EXISTE: {0}", code);
        }
    }

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

    /**
     * Metodo que obtiene el numero correspondiente para el codigo interno del usuario
     * @return
     * @throws Exception
     */
    private Integer getInternalCode() throws Exception {
        Sequence sequence = new Sequence();
        return Integer.valueOf(sequence.getNextValue("INTERNALCODE").toString());
    }
     private static String JPQL_USER ="select t.pk from TsafeUser t where t.pk = :usercode " +
     		" and t.companycode = :company";
     
     private String findUser(String usercode,Integer company) throws Exception{
    	 String code;  	 
    	 Query qry = PersistenceHelper.getEntityManager().createQuery(JPQL_USER);
    	 qry.setParameter("usercode", usercode);
    	 qry.setParameter("company", company);    	 
    	 try {
    		 code = (String)qry.getSingleResult();	
 		} catch (NoResultException e) {
 			return code =null;			
 		}
         return code;
     }     
     
     
    
}
