/*
 * Copyright
 *   2007 axYus - www.axyus.com
 *   2009 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.dgfip.xemelios.web.search;

import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.auth.XemeliosUser;
import fr.gouv.finances.dgfip.xemelios.common.config.ChampModel;
import fr.gouv.finances.dgfip.xemelios.common.config.DocumentModel;
import fr.gouv.finances.dgfip.xemelios.common.config.ElementModel;
import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import fr.gouv.finances.dgfip.xemelios.utils.XmlUtils;
import fr.gouv.finances.dgfip.xemelios.web.AttributeHelper;
import fr.gouv.finances.dgfip.xemelios.web.gwt.server.service.SearchSessionContainer;
import fr.gouv.finances.dgfip.xemelios.web.gwt.server.service.SearchSessionContainer.SearchSession;
import fr.gouv.finances.dgfip.xemelios.web.utils.StdDispatchAction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * Calculates aggregate value of a column
 * @author Christophe Marchand <christophe.marchand@axyus.com>
 */
public class AggregateAction extends StdDispatchAction {

    @Override
    protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String searchSessionId = request.getParameter("searchSessionId");
        String idColumn = request.getParameter("idCol");
        String operator = request.getParameter("operator");

        HttpSession session = request.getSession();
        XemeliosUser user = AttributeHelper.getUser(session);

        SearchSession searchSession = SearchSessionContainer.getInstance(session).getSearchSession(searchSessionId);

        ElementModel elementModel = searchSession.getElementModel();
        DocumentModel dm = searchSession.getDocumentModel();
        ListeResultatModel lrm = searchSession.getDataResultSet().getListeResultatModel();
        ChampModel cm = lrm.getChamps().get(idColumn);
        String xpath = lrm.getParent().getPath().getFormattedPath()+"/"+cm.getPath().getFormattedPath();
        xpath = XmlUtils.normalizeNS(xpath,dm.getNamespaces());
        final String resultat = DataLayerManager.getImplementation().calculateAggregate(
                dm,
                elementModel.getParent(),
                xpath,
                operator,
                cm,
                searchSession.getDataResultSet(),
                user);
        StringBuffer sb = new StringBuffer();
        Pair[] operators = DataLayerManager.getImplementation().getAggregateOperators(cm.getDatatype());
        String opLib = null;
        for(Pair p:operators)
            if(p.key.equals(operator)) {
                opLib=p.libelle;
                break;
            }
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><resultat>");
        if(opLib!=null) {
            sb.append(opLib).append(" de ").append(cm.getLibelle()).append(": ");
        }
        sb.append(resultat).append("</resultat>");

        byte[] data = sb.toString().getBytes("UTF-8");
        response.setContentType("text/xml");
        response.setContentLength(data.length);
        response.getOutputStream().write(data);
        response.getOutputStream().flush();

        return null;
    }


}
