/*
 * 
 */
package com.fp.bpmlib.transaction;

import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.text.MessageFormat;
import java.util.List;

import com.fp.bpmlib.db.BPMProperties;
import com.fp.common.files.StreamHelper;
import com.fp.common.logger.APPLogger;
import com.fp.common.properties.PropertiesHandler;
import com.fp.dto.rules.TransactionRule;
import com.fp.dto.save.SaveRequest;
import com.fp.persistence.pbpm.gene.TbpmRules;

// TODO: Auto-generated Javadoc
/**
 * Class PackageGetter encargada de.
 * 
 * @author gfiallos
 */
public class PackageGetter extends TransactionRule {

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

    /**
     * Normal process.
     * 
     * @param pReq the req
     * @return save request
     * @throws Exception la exception
     */
    @Override
    public SaveRequest normalProcess(SaveRequest pReq) throws Exception {
        PropertiesHandler ph = BPMProperties.getInstance();
        List<Object> data = pReq.getBeans().get("TBPMRULES").getModifiedRecords();
        for (Object object : data) {
            TbpmRules rule1 = (TbpmRules) object;
            if (ph.getStringValue(BPMProperties.GUVNOR_SECURITY_BASIC_AUTHENTICATION).compareTo("enabled") == 0) {
                Authenticator.setDefault(new GuvnorAuthenticator());
            }
            String url = MessageFormat.format(ph.getStringValue(BPMProperties.GUVNOR_URL), rule1.getPackagename(), rule1.getSnapshot());
            URL udata = new URL(url);
            InputStream ib = null;
            try {
                ib = udata.openStream();
                rule1.setContent(StreamHelper.streamToBytes(ib));                
                pReq.getResponse().put("RELOAD", "OK");
            } catch (IOException e) {
                APPLogger.getLogger().debug("IOError: " + e);
                pReq.getResponse().put("RELOAD", "ERROR");
            } finally {
            	if(ib != null){
            		ib.close();
            	}
            }
            // InputStream ib = udata.openStream();
            // rule1.setContent(StreamHelper.streamToBytes(ib));
        }
        return pReq;
    }

    /**
     * Reverse process.
     * 
     * @param pReq the req
     * @return save request
     * @throws Exception la exception
     */
    @Override
    public SaveRequest reverseProcess(SaveRequest pReq) throws Exception {
        return pReq;
    }

}

/**
 * Clase empleada para la autenticación con Guvnor
 * 
 * @author gfiallos
 * 
 */
class GuvnorAuthenticator extends Authenticator {

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        try {
            PropertiesHandler ph = BPMProperties.getInstance();
            return new PasswordAuthentication(ph.getStringValue(BPMProperties.GUVNOR_SECURITY_USERNAME), ph.getStringValue(
                    BPMProperties.GUVNOR_SECURITY_PASSWORD).toCharArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
}