/*
 * 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.xemelios.common.config.ChampModel;
import fr.gouv.finances.dgfip.xemelios.common.config.ListeResultatModel;
import fr.gouv.finances.dgfip.xemelios.common.config.PjRefHandler;
import fr.gouv.finances.dgfip.xemelios.data.DataHandler;
import fr.gouv.finances.dgfip.xemelios.data.DataResultSet;
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.ParametreManager;
import fr.gouv.finances.dgfip.xemelios.web.utils.StdDispatchAction;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author chm
 */
public class SimpleExportAction extends StdDispatchAction {
    public static final String LINE_HEADER="";
    public static final String FIELD_SEPARATOR = ";";
    public static final String LINE_SEPARATOR = "\r\n";

    @Override
    protected ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String searchSessionId = request.getParameter("searchSessionId");
        SearchSession ss = SearchSessionContainer.getInstance(request.getSession()).getSearchSession(searchSessionId);


        DataResultSet dataResultSet = ss.getDataResultSet();
        ListeResultatModel lrm = dataResultSet.getListeResultatModel();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter writer = new OutputStreamWriter(baos);
        // on se repositionne sur la bonne page
        dataResultSet.setPage(dataResultSet.getCurrentPage());
        for (ChampModel champModel : lrm.getListeChamps()) {
            if(champModel.isAfficheDefaut()) {
                writer.write(champModel.getLibelle());
                writer.write(FIELD_SEPARATOR);
            }
        }
        writer.write(LINE_SEPARATOR);
        
        while(dataResultSet.hasNext()) {
            writer.write(LINE_HEADER);
            DataHandler dataHandler = dataResultSet.next();
            int i = 0;
            for (ChampModel champModel : lrm.getListeChamps()) {
                if(!champModel.isAfficheDefaut()) {
                    // nothing to do, but do not continue !
                } else {
                    Object value = dataHandler.getValueAtColumn(i);
                    String sVal = value != null ? value.toString() : null;
                    if(value instanceof PjRefHandler) {
                        writer.write("...");
                    } else {
                        if (value instanceof Date) {
                            SimpleDateFormat sdf = new SimpleDateFormat(ParametreManager.getDisplayDateFormat());
                            sVal = sdf.format((Date) value);
                            // TODO: eventuellement, passer la date en numerique (genre millisecondes depuis...) pour pouvoir trier sur la valeur numérique
                        }
                        if(sVal!=null) writer.write(sVal);
                    }
                    writer.write(FIELD_SEPARATOR);
                }
                i++;
            }
            writer.write(LINE_SEPARATOR);
        }
        writer.flush(); writer.close();
        response.setContentType("application/csv");
        response.addHeader("Content-disposition", "attachment; filename=export.csv");
        response.setContentLength(baos.size());
        response.getOutputStream().write(baos.toByteArray());
        response.getOutputStream().flush();

        return null;
    }


}
