/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fr.gouv.finances.cp.xemelios.erar.plugins;

import fr.gouv.finances.dgfip.xemelios.common.config.PropertyModel;
import fr.gouv.finances.dgfip.xemelios.data.DataConfigurationException;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
import fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer;
import fr.gouv.finances.cp.xemelios.data.impl.mysql.MySqlDataResultSetDocGenerator;
import fr.gouv.finances.dgfip.xemelios.data.impl.sqlconfig.TDocument;
import fr.gouv.finances.dgfip.xemelios.data.impl.sqlconfig.TEtat;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.plugins.SearchPlugin;
import java.io.File;
import java.text.DecimalFormat;
import org.apache.log4j.Logger;

/**
 *
 * @author chm
 */
public class TotalisationDebiteur extends SearchPlugin {
    private static final Logger logger = Logger.getLogger(TotalisationDebiteur.class);
    private TDocument pc = null;
    MySqlDataLayer layer;
    private TEtat ec = null;
    private String CRLF="\n";
    private String request;
    private DecimalFormat df;

    public TotalisationDebiteur(XemeliosUser user) {
        super(user);
        try {
            layer = (MySqlDataLayer)DataLayerManager.getImplementation();
        } catch(Exception ex) {
            logger.error("<init>",ex);
        }
        
    }
    protected static String unnull(String  s) { return s!=null?s:""; }
 
    public void computeParameters() throws Exception {
        pc = layer.getPersistenceConfig(getDocumentModel(),getUser()).getLayer("mysql").getDocument(getDocumentModel().getId());
        ec = pc.getEtat(getEtatModel().getId());
        for(PropertyModel pm:getPluginModel().getProperties()) {
            if("request".equals(pm.getName())) request=pm.getValue();
        }
    }

    protected String getParameterizedRequest(final String rq) throws DataConfigurationException {
        String data = rq;
        // first, change table names
        int posParam = data.indexOf("${");
        while(posParam>=0) {
            int posEnd = data.indexOf('}',posParam);
            if(posEnd<0) throw new DataConfigurationException("Invalid request: "+rq);
            String paramName = data.substring(posParam+2,posEnd);
            String paramValue = null;
            if(paramName.startsWith("table-")) {
                String typeTable = paramName.substring(6);
                if(typeTable.startsWith("index-")) {
                    String indexId = typeTable.substring(6);
                    paramValue = ec.getIndexTable(indexId).getBaseName();
                } else {
                    throw new DataConfigurationException("can only deal with index tables: ${"+paramName+"}");
                }
            } else if(paramName.equals("collectivite")) {
                paramValue=getCollectivite().key;
            } else if(paramName.equals("budget")) {
                paramValue = getBudget().key;
            } else {
                throw new DataConfigurationException("can only deal with tables parameters: ${"+paramName+"}");
            }
            if(paramValue==null) throw new DataConfigurationException("no value found for param ${"+paramName+"}");
            data = data.replaceAll("\\$\\{"+paramName+"\\}",paramValue);
            // next round
            posParam = data.indexOf("${");
        }
//        logger.debug(data);
        
        // next, change parameters
        int pos = data.indexOf("##");
        while(pos>=0) {
            int endPos=data.indexOf("##",pos+2);
            if(endPos<0) throw new DataConfigurationException("invalid expression near "+data.substring(pos));
            String pattern=data.substring(pos,endPos+2);
            String paramName = pattern.substring(2,pattern.length()-2);
//            logger.debug("itemName="+itemName);
            String paramValue=getParameters().get(paramName);
            if (paramValue!=null) {
                data = data.replace(pattern,paramValue);
            } else {
                data = data.replace(pattern,"\"\"");
            }
            pos = data.indexOf("##");
        }
        return data;
    }

    @Override
    public DataResultSet getResultSet() throws Exception {
        try {
            String rq = getParameterizedRequest(request);
            String xslFileName = getElementModel().getParent().getParent().getParameters().getParameter("xsl.doc.generator").getValue();
            File xslFile = new File(new File(getElementModel().getParent().getParent().getBaseDirectory()),xslFileName);
            return new MySqlDataResultSetDocGenerator(getElementModel(),getCollectivite(),getBudget(),getElementModel().getPath().getPath(),rq,getListeResultat(),layer,xslFile);
        } catch(Exception ex) {
            logger.error(ex);
        }
        return layer.getEmptyDataResultSet();
    }

}
