/*
 * Copyright 
 *   2005 axYus - www.axyus.com
 *   2005 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 General Public License as published by
 * the Free Software Foundation; either version 2 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU 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.plugins.paye;

import fr.gouv.finances.cp.xemelios.data.impl.mysql.MySqlDataResultSet;
import java.util.Vector;

import javax.swing.SwingUtilities;

import org.apache.log4j.Logger;

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.DataLayerManager;
import fr.gouv.finances.cp.xemelios.data.DataResultSet;
import fr.gouv.finances.cp.xemelios.data.impl.MySqlDataLayer;
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;

/**
 * Plugin permettant de trouver les agents sortants ou entrants entre 2 periodes.
 * Ce plugin cherche les agents qui sont presents dans la periode 1 (year1 - month1)
 * et pas dans la periode 2 (year2 - month2)
 * @author chm
 */
public class EntrantsSortants extends SearchPlugin {
    private static final Logger logger = Logger.getLogger(EntrantsSortants.class);
    private String year1, year2, month1, month2;
    private boolean bothJob = false;

    public EntrantsSortants() {
        super();
    }


    @Override
    public void computeParameters() throws Exception {
        year1 = getParameters().get("VALEUR:year1");
        month1 = getParameters().get("VALEUR:month1");
        year2 = getParameters().get("VALEUR:year2");
        month2 = getParameters().get("VALEUR:month2");
        StringBuffer error = new StringBuffer();
        boolean hasError = false;
        if(year1==null || year1.length()==0) {
            error.append("Le champ année 1 doit êter rempli\n");
            hasError = true;
        }
        if(year2==null || year2.length()==0) {
            error.append("Le champ année 2 doit êter rempli\n");
            hasError = true;
        }
        if(month1==null || month1.length()==0) {
            error.append("Le champ mois 1 doit êter rempli\n");
            hasError = true;
        }
        if(month2==null || month2.length()==0) {
            error.append("Le champ mois 2 doit êter rempli\n");
            hasError = true;
        }
        try { Integer.parseInt(year1); } catch(NumberFormatException nfEx) {
        	error.append("Le champ année 1 ne contient pas une année valide\n");
        	hasError = true;
        }
        try { Integer.parseInt(year2); } catch(NumberFormatException nfEx) {
        	error.append("Le champ année 2 ne contient pas une année valide\n");
        	hasError = true;
        }
        if(hasError) {
            logger.error(error.toString());
            throw new Exception(error.toString());
        }
    }
    

    @Override
	public DataResultSet doInBackground() throws Exception {
        computeParameters();
// gets the persistence
        MySqlDataLayer dl = (MySqlDataLayer)DataLayerManager.getImplementation();
        TDocument pc = dl.getPersistenceConfig(getEtatModel().getParent()).getLayer("mysql").getDocument(getEtatModel().getParent().getId());
        TEtat sec = pc.getEtat(getEtatModel().getId());
        Vector<PropertyModel> props = getPluginModel().getProperties();

        for(PropertyModel property:props) {
            if(property.getName().equals("entrants.sortants")) {
                bothJob = Boolean.parseBoolean(property.getValue());
            }
        }
        StringBuilder request = new StringBuilder();
        request.append("SELECT SQL_CALC_FOUND_ROWS DOC_ID, ANNEE, MOIS FROM ").append(sec.getIndexTable("T1"));
        request.append(" WHERE COLLECTIVITE='").append(getCollectivite().key).append("' AND BUDGET='").append(getBudget().key);
        request.append("' AND ((ANNEE=").append(year1).append(" AND MOIS='").append(month1).append("') || (ANNEE=").append(year2).append(" AND MOIS='").append(month2).append("')) ");
        request.append("GROUP BY AGENT_MATRICULE HAVING COUNT(AGENT_MATRICULE)=1 ");
        if(!bothJob) request.append("AND ANNEE=").append(year1).append(" AND MOIS='").append(month1).append("'");
        ListeResultatModel lrm = getElementModel().getListeResultat();
        return new MySqlDataResultSet(getElementModel(),getCollectivite(),getBudget(),"/n:DocumentPaye/n:DonneesIndiv/n:PayeIndivMensuel",request.toString(),lrm,dl);
    }
    @Override
	public void done() {
        try {
            DataResultSet rs = (DataResultSet)get();
            Runnable code = new ResultDisplayerThread(rs,getElementModel().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();
        }
    }

}
