/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2007 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.data.impl.mysql;

import fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer;
import javax.swing.SwingUtilities;

import fr.gouv.finances.cp.utils.ui.DisplayExceptionDlg;
import fr.gouv.finances.cp.xemelios.common.config.ListeResultatModel;
import fr.gouv.finances.cp.xemelios.common.config.PropertyModel;
import fr.gouv.finances.cp.xemelios.data.DataConfigurationException;
import fr.gouv.finances.cp.xemelios.data.DataLayerManager;
import fr.gouv.finances.cp.xemelios.data.DataResultSet;
import fr.gouv.finances.cp.xemelios.data.impl.sqlconfig.TDocument;
import fr.gouv.finances.cp.xemelios.data.impl.sqlconfig.TEtat;
import fr.gouv.finances.cp.xemelios.plugins.SearchPlugin;
import fr.gouv.finances.cp.xemelios.ui.search.ResultDisplayerThread;

/**
 * This class is designed to execute simple requests
 * @author chm
 *
 */
public class SqlGenericSearchPlugin extends SearchPlugin {
//	private static Logger logger = Logger.getLogger(SqlGenericSearchPlugin.class);
    public static final transient String PROPERTY_REQUEST = "request";
    public static final transient String PROPERTY_XPATH = "xpath";
    private String request, xpath;
    private MySqlDataLayer layer = null;
    private TDocument pc = null;
    private TEtat ec = null;

    public SqlGenericSearchPlugin() {
        super();
    // TODO Auto-generated constructor stub
    }

    @Override
    public DataResultSet doInBackground() throws Exception {
        ListeResultatModel lrm = getElementModel().getListeResultat();
        return new MySqlDataResultSet(getElementModel(), getCollectivite(), getBudget(), xpath, getParameterizedRequest(request), lrm, layer);
    }

    @Override
    public void computeParameters() throws Exception {
        for (PropertyModel pm : getPluginModel().getProperties()) {
            if (PROPERTY_REQUEST.equals(pm.getName())) {
                request = pm.getValue();
            } else if (PROPERTY_XPATH.equals(pm.getName())) {
                xpath = pm.getValue();
            }
        }
        try {
            layer = (MySqlDataLayer) DataLayerManager.getImplementation();
            pc = layer.getPersistenceConfig(getDocumentModel()).getLayer(layer.getLayerName()).getDocument(getDocumentModel().getId());
            ec = pc.getEtat(getEtatModel().getId());
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }

    protected String getParameterizedRequest(final String rq) throws DataConfigurationException {
        String data = rq;
        // first, change table name
        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("${");
        }

        // 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);
            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 void done() {
        try {
            DataResultSet rs = (DataResultSet) get();
            Runnable code = new ResultDisplayerThread(rs, getListeResultat(), getStart(), getElementModel(), getSearchWindow());
            if (SwingUtilities.isEventDispatchThread()) {
                code.run();
            } else {
                try {
                    SwingUtilities.invokeAndWait(code);
                } catch (Throwable t) {
                }
            }
            firePropertyChange("COMPLETED", Boolean.FALSE, Boolean.TRUE);
        } catch (Throwable t) {
            DisplayExceptionDlg.displayException(getOwner(), t);
        } finally {
            setProgressVisible(false);
            super.done();
        }
    }
}
