/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.das2.datum;

import java.io.File;
import java.io.FilenameFilter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

/**
 * Experiment with a tool for quickly creating time templates.  This has 
 * a fair amount of work to be done, but I think it would be useful:
 * 1. variable length fields need to be supported.
 * 2. there's a bug where the indices sent to the field picker are not adjusted for template lengths.
 * 3. support for recognizing enums.
 * 4. controls/columns added for enums in table.
 * @author jbf
 */
public class TimeTemplator extends javax.swing.JPanel {
    
    private String[] formatted;

    /**
     * Creates new form TimeTemplator
     */
    public TimeTemplator() {
        initComponents();
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        templateTextField = new javax.swing.JTextField();
        fieldTypeButton = new javax.swing.JButton();
        sortByButton = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Title 1", "Title 2"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        templateTextField.setText("rte_2066281937_20151101_050235_jbf.xml");
        templateTextField.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                templateTextFieldMouseClicked(evt);
            }
        });

        fieldTypeButton.setText("Field Type...");
        fieldTypeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldTypeButtonActionPerformed(evt);
            }
        });

        sortByButton.setText("Sort By");
        sortByButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sortByButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addComponent(templateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(fieldTypeButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(sortByButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {fieldTypeButton, sortByButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(templateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(fieldTypeButton)
                    .addComponent(sortByButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void templateTextFieldMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_templateTextFieldMouseClicked
        if ( evt.getClickCount()==2 ) {
            
        }
    }//GEN-LAST:event_templateTextFieldMouseClicked

    private void fieldTypeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldTypeButtonActionPerformed
        int i0= templateTextField.getSelectionStart();
        int i1= templateTextField.getSelectionEnd();
        TimeTemplatorFieldPicker ttfp= new TimeTemplatorFieldPicker();
        ttfp.setFormatted(formatted);
        ttfp.setTemplate(templateTextField.getText());
        ttfp.setSelection(i0,i1);
        JDialog d= new JDialog((JDialog)SwingUtilities.getWindowAncestor(this),true);
        d.getContentPane().add(ttfp);
        d.pack();
        d.setLocationRelativeTo(this);
        d.setVisible(true);
        templateTextField.setText(ttfp.getTemplate());
    }//GEN-LAST:event_fieldTypeButtonActionPerformed

    private void sortByButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sortByButtonActionPerformed
        final int i0= templateTextField.getSelectionStart();
        final int i1= templateTextField.getSelectionEnd();
        if ( i0==i1 ) {
            setFormattedTable( formatted );
            return;
        }
        int imax= Integer.MIN_VALUE;
        int imin= Integer.MAX_VALUE;
        if ( this.formatted!=null ) {
            Map<String,Integer> other= new LinkedHashMap();
            for ( String formatted1 : formatted ) {
                if ( i0>=formatted1.length() ) {
                    continue;
                }
                String s = formatted1.substring(i0, i1); // extract the field
                try {
                    int i=  Integer.parseInt(s);
                    imin= Math.min( imin, i );
                    imax= Math.max( imax, i );
                } catch ( NumberFormatException ex ) {
                    Integer i= other.get(s);
                    if ( i==null ) {
                        other.put( s, 1 );
                    } else {
                        other.put( s, i+1 );
                    }
                }
            }
            
            List<String> sformatted= Arrays.asList(formatted);
            Collections.sort( sformatted, new Comparator() {
                    @Override
                    public int compare(Object o1, Object o2) {
                        String s1= (String)o1;
                        String s2= (String)o2;
                        if ( i0>s1.length() ) {
                            return 1;
                        } else if ( i0>s2.length() ) {
                            return -1;
                        }
                        s1= s1.substring(i0,i1);
                        s2= s2.substring(i0,i1);
                        return s1.compareTo(s2);
                    }
                } );
            
            setFormattedTable( sformatted.toArray(new String[sformatted.size()]) );
        }
    }//GEN-LAST:event_sortByButtonActionPerformed

    private void setFormattedTable( String[] formatted ) {
        TimeParser tp;
        try {
            tp = TimeParser.create(templateTextField.getText());
        } catch ( IllegalArgumentException ex ) {
            tp= null;
        }
        DefaultTableModel dtm= new DefaultTableModel(formatted.length,2);
        for ( int i=0; i<formatted.length; i++ ) {
            dtm.setValueAt( formatted[i], i, 0 );
            try {
                dtm.setValueAt( tp.parse( formatted[i] ).getTimeRange().toString(), i, 1 );
            } catch ( ParseException ex ) {
                dtm.setValueAt( "", i, 1 );
            } catch ( IllegalArgumentException ex ) {
                dtm.setValueAt( "", i, 1 );
            }
            
        }
        this.jTable1.setModel(dtm);
        this.formatted= formatted;
    }
    
    public void setFormatted( String[] formatted ) {
        setFormattedTable(formatted);
        this.templateTextField.setText( formatted[0] );
    }
    
    public static void main( String[] args ) {
        String[] ll= new File("/home/jbf/uploads/").list( new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".xml");
            }
        });
        TimeTemplator me= new TimeTemplator();
        me.setFormatted(ll);
        JOptionPane.showConfirmDialog(null, me);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton fieldTypeButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton sortByButton;
    private javax.swing.JTextField templateTextField;
    // End of variables declaration//GEN-END:variables
}