/*
 * 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.auth.impl.std.db.ui;

import fr.gouv.finances.dgfip.xemelios.auth.impl.std.db.DataHelper;
import fr.gouv.finances.dgfip.utils.Pair;
import fr.gouv.finances.dgfip.xemelios.common.Constants;
import fr.gouv.finances.dgfip.xemelios.common.NetAccess;
import fr.gouv.finances.dgfip.xemelios.data.DataLayerManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import java.util.zip.GZIPInputStream;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 *
 * @author chm
 */
public class PnlCreateCollectivite extends javax.swing.JPanel {
    private static final Logger logger = Logger.getLogger(PnlCreateCollectivite.class);
    private Vector<Pair> natIds;
    private DlgSelectCollectivite parent;

    /** Creates new form PnlCreateCollectivite */
    public PnlCreateCollectivite(DlgSelectCollectivite parent) {
        super();
        this.parent=parent;
        natIds = new Vector<Pair>();
        for(String key:DlgCollectivitesUtilisateur.naturesIdentifiants.keySet()) {
            natIds.add(new Pair(key,DlgCollectivitesUtilisateur.naturesIdentifiants.get(key)));
        }
        initComponents();
    }

    public List<DataHelper.CollectiviteLib> getSelectedData() {
        ArrayList<DataHelper.CollectiviteLib> ret = new ArrayList<DataHelper.CollectiviteLib>();
        if(dfIdentifiant.getText().length()>0 && dfLibelle.getText().length()>0) {
            DataHelper.CollectiviteLib coll = new DataHelper.CollectiviteLib(((Pair)cbxNatId.getSelectedItem()).key, dfIdentifiant.getText(), dfLibelle.getText());
            DataHelper.createCollectivite(coll);
            ret.add(coll);
        }
        return ret;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        lblNatId = new javax.swing.JLabel();
        cbxNatId = new javax.swing.JComboBox(natIds);
        lblClef = new javax.swing.JLabel();
        dfIdentifiant = new javax.swing.JTextField();
        lblLibelle = new javax.swing.JLabel();
        dfLibelle = new javax.swing.JTextField();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        pbLoadRef = new javax.swing.JButton();

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Créer une nouvelle collectivité"));

        lblNatId.setText("Nature Identifiant");

        lblClef.setText("Identifiant");

        lblLibelle.setText("Libellé");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(lblNatId)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(cbxNatId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(lblClef)
                            .add(lblLibelle))
                        .add(56, 56, 56)
                        .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(dfIdentifiant)
                            .add(dfLibelle, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 357, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(106, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblNatId)
                    .add(cbxNatId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblClef)
                    .add(dfIdentifiant, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lblLibelle)
                    .add(dfLibelle, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Importer le référentiel de Collectivités / Budgets"));

        jLabel1.setText("<html>\n<p>Permet de charger le référentiel de collectivités / budgets maintenu par la DGFiP pour Helios.</p>\n<p>Ce référentiel est disponible sous la forme d'un unique fichier déposé sur www.xemelios.org.</p>\n\n<p>Ce référentiel est maintenu à jour et republié régulièrement.</p>\n<p>L'installation du référentiel peut être longue et bloquer Xemelios pendant longtemps.</p>\n</html>");

        pbLoadRef.setText("Installer le référentiel");
        pbLoadRef.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbLoadRefActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jLabel1)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                        .add(pbLoadRef)
                        .addContainerGap())))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(pbLoadRef)
                .addContainerGap(13, Short.MAX_VALUE))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void pbLoadRefActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbLoadRefActionPerformed
        DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        parent.getGlassPane().setVisible(true);
        try {
            String actualDate = DataLayerManager.getImplementation().getParameterValue("referentiel.collectivite.last.update");
            Date actualRefDate = actualDate!=null ? sdf.parse(actualDate) : new Date(0);
            HttpClient client = NetAccess.getHttpClient();
            URL refUrl = new URL(System.getProperty(Constants.SYS_PROP_AUTH_REF_URL,"http://www.xemelios.org/collectivites/referentiel.xml"));
            GetMethod meth = new GetMethod(refUrl.toURI().toString());
            int httpRet = client.executeMethod(meth);
            if(httpRet>300) throw new Exception(meth.getStatusText());
            InputStream is = meth.getResponseBodyAsStream();
            DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder domBuilder = domFactory.newDocumentBuilder();
            Document refColls = domBuilder.parse(is);
            XPathFactory xpf = new net.sf.saxon.xpath.XPathFactoryImpl();
            XPath xp = xpf.newXPath();
            String fileToLoad = null;
            Date updateDate = actualRefDate;
            ArrayList<Element> lst = (ArrayList<Element>)xp.evaluate("/ref-collectivites/referentiel", refColls, XPathConstants.NODESET);
            for(Element el:lst) {
                String fileName = (String)xp.evaluate("./file/text()",el);
                Date date = sdf.parse((String)xp.evaluate("./date/text()",el));
                if(date.after(updateDate)) {
                    fileToLoad = fileName;
                    updateDate = date;
                }
            }
            if(fileToLoad==null) {
                JOptionPane.showMessageDialog(this, "Votre référentiel est à jour.");
            } else {
                URL url = new URL(refUrl,fileToLoad);
                meth = new GetMethod(url.toURI().toString());
                httpRet = client.executeMethod(meth);
                if(httpRet>300) throw new Exception(meth.getStatusText());
                is = meth.getResponseBodyAsStream();
                GZIPInputStream gzis = new GZIPInputStream(is);
                BufferedReader br = new BufferedReader(new InputStreamReader(gzis));
                String l = null;
                while((l=br.readLine()) != null) {
                    saveLine(l);
                }
                br.close();
                DataLayerManager.getImplementation().setParameterValue("referentiel.collectivite.last.update", sdf.format(updateDate));
            }
        } catch(Exception ex) {
            logger.error("loadRef",ex);
        } finally {
            parent.getGlassPane().setVisible(false);
        }
    }//GEN-LAST:event_pbLoadRefActionPerformed

    private void saveLine(String line) {
        String[] vals = line.split(";");
        String siret = vals[5];
        String idColl = vals[1]+vals[3]+vals[4];
        String libelle = vals[7];
        String codic = vals[1];
        String libCodic = vals[2];
        DataHelper.updateCollectivite(new DataHelper.CollectiviteLib("SIRET",siret,libelle));
        DataHelper.updateCollectivite(new DataHelper.CollectiviteLib("IDCOLL",idColl,libelle));
        DataHelper.updateCollectivite(new DataHelper.CollectiviteLib("CODIC",codic,libCodic));
        DataHelper.updateCollectivite(new DataHelper.CollectiviteLib("VARIABLE",siret,libelle));
        DataHelper.updateCollectivite(new DataHelper.CollectiviteLib("VARIABLE",idColl,libelle));
        DataHelper.updateCollectivite(new DataHelper.CollectiviteLib("VARIABLE",codic,libCodic));

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cbxNatId;
    private javax.swing.JTextField dfIdentifiant;
    private javax.swing.JTextField dfLibelle;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel lblClef;
    private javax.swing.JLabel lblLibelle;
    private javax.swing.JLabel lblNatId;
    private javax.swing.JButton pbLoadRef;
    // End of variables declaration//GEN-END:variables

}
