/*
 * Copyright
 *   2010 axYus - www.axyus.com
 *   2010 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.ui.admin;

import fr.gouv.finances.dgfip.xemelios.common.Constants;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.TreeSet;
import javax.swing.AbstractListModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.log4j.Logger;

/**
 *
 * @author  chm
 */
public class PnlSystemProperties extends javax.swing.JPanel implements ParamSaver  {
    private static final Logger logger = Logger.getLogger(PnlSystemProperties.class);
    private TreeSet<Prop> properties;
    private LM listModel;
    private Prop currentProp;
    
    /** Creates new form PnlUpdate */
    public PnlSystemProperties() {
        preInitComponents();
        initComponents();
        postInitComponents();
    }

    protected void preInitComponents() {
        properties = new TreeSet<Prop>();
        for(Object key:System.getProperties().keySet()) {
            String propName = key.toString();
            if(propName.startsWith("xemelios")) {
                Prop prop = new Prop(propName,System.getProperty(propName));
                properties.add(prop);
            }
        }
        // on va chercher celles existantes (potentiellement)
        Class clazz = Constants.class;
        Field[] fields = clazz.getFields();
        for(int i=0;i<fields.length;i++) {
            if(fields[i].getType().equals(String.class) && (fields[i].getModifiers() | (Modifier.PUBLIC + Modifier.STATIC + Modifier.FINAL))>0) {
                try {
                    String propName = fields[i].get(null).toString();
                    if(propName.startsWith("xemelios") || fields[i].getName().startsWith("SYS_PROP")) {
                        Prop p = new Prop(propName,null);
                        if(!properties.contains(p)) properties.add(p);
                    }
                } catch(Exception ex) {
                    logger.debug("while introspecting",ex);
                }
            }
        }
        listModel = new LM(properties);
    }

    protected void postInitComponents() {
        lstProps.addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                currentProp = (Prop)lstProps.getSelectedValue();
                if(currentProp!=null) {
                    dfValue.setEditable(true);
                    dfValue.setText(currentProp.getPropValue());
                    pbSet.setEnabled(true);
                } else {
                    dfValue.setEditable(false);
                    dfValue.setText(null);
                    pbSet.setEnabled(false);
                }
            }
        });

    }
    
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstProps = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        dfValue = new javax.swing.JTextField();
        pbSet = new javax.swing.JButton();

        jLabel1.setText("Propriétés systèmes");

        lstProps.setModel(listModel);
        lstProps.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(lstProps);

        jLabel2.setText("Valeur");

        pbSet.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fr/gouv/finances/cp/xemelios/ui/resources/edit-redo.png"))); // NOI18N
        pbSet.setToolTipText("Enregistrer la valeur");
        pbSet.setEnabled(false);
        pbSet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pbSetActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel1)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(dfValue, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 287, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(pbSet)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(dfValue, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(pbSet, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void pbSetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pbSetActionPerformed
        if(currentProp!=null) {
            String value = dfValue.getText();
            if(value!=null && value.length()==0) value = null;
            currentProp.setPropValue(value);
            System.setProperty(currentProp.getPropName(), value);
        }
    }//GEN-LAST:event_pbSetActionPerformed

    public void saveConfiguration() { }
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField dfValue;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList lstProps;
    private javax.swing.JButton pbSet;
    // End of variables declaration//GEN-END:variables

    private class Prop implements Comparable {
        private String propName = null;
        private String propValue = null;
        private String documentation = null;

        public Prop(String propName, String propValue) {
            super();
            this.propName=propName;
            this.propValue=propValue;
        }
        public Prop(String propName, String propValue, String documentation) {
            this(propName, propValue);
            this.documentation=documentation;
        }
        @Override
        public String toString() { return propName; }

        public String getDocumentation() {
            return documentation;
        }

        public void setDocumentation(String documentation) {
            this.documentation = documentation;
        }

        public String getPropName() {
            return propName;
        }

        public void setPropName(String propName) {
            this.propName = propName;
        }

        public String getPropValue() {
            return propValue;
        }

        public void setPropValue(String propValue) {
            this.propValue = propValue;
        }
        public boolean equals(Prop other) { return propName.equals(other.getPropName()); }

        public int compareTo(Object o) {
            Prop other = (Prop)o;
            return propName.compareTo(other.getPropName());
        }
    }

    private class LM extends AbstractListModel {
        private Prop[] data;

        public LM(TreeSet<Prop> properties) {
            super();
            data = new Prop[properties.size()];
            properties.toArray(data);
        }

        public int getSize() {
            return data.length;
        }

        public Object getElementAt(int index) {
            return data[index];
        }

    }
}
