
package org.autoplot;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.das2.qds.QDataSet;
import org.das2.qds.ops.Ops;
import org.das2.qds.util.QDataSetTableModel;
import org.das2.util.LoggerManager;
import org.das2.util.monitor.NullProgressMonitor;
import org.das2.util.monitor.ProgressMonitor;

/**
 *
 * @author jbf
 */
public final class ExportDataBundle extends javax.swing.JPanel {

    private static final Logger logger= LoggerManager.getLogger("autoplot.export");
    /**
     * Creates new form ExportDataWow
     */
    public ExportDataBundle() {
        initComponents();
        namedURIListTool1.setShowIds(false);
        refresh();
    }

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

        jPanel2 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        namedURIListTool1 = new org.autoplot.jythonsupport.ui.NamedURIListTool();
        exportDataFormatPanel1 = new org.autoplot.ExportDataFormatPanel();

        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

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

        jSplitPane1.setRightComponent(jScrollPane1);

        jButton1.setText("Load");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        namedURIListTool1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                namedURIListTool1PropertyChange(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(namedURIListTool1, javax.swing.GroupLayout.DEFAULT_SIZE, 571, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(namedURIListTool1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        jSplitPane1.setLeftComponent(jPanel1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(exportDataFormatPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(0, 0, 0)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(exportDataFormatPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void namedURIListTool1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_namedURIListTool1PropertyChange
        
    }//GEN-LAST:event_namedURIListTool1PropertyChange

    boolean updating= false;
    
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Runnable run= new Runnable() {
            @Override
            public void run() {
                refresh();
                updating= false;
                jButton1.setEnabled(true);
            }
        };
        if ( updating ) {
            logger.fine("already updating");
        } else {
            jButton1.setEnabled(false);
            updating= true;
            new Thread(run).start();
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    
    private ProgressMonitor createProgressMonitor() {
        final ProgressMonitor result= new NullProgressMonitor();
        final javax.swing.Timer t= new javax.swing.Timer( 100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jButton1.setText(result.getTaskProgress()+"/"+result.getTaskSize());
                if ( result.isFinished() || result.isCancelled() ) {
                    ((javax.swing.Timer)e.getSource()).stop();
                    jButton1.setText("Load");
                }
            }
        });
        t.setRepeats(true);
        t.start();
        return result;
    }
  
    private void updateDataSet() {
        String[] ids= namedURIListTool1.getIds();
        String[] uris= namedURIListTool1.getUris();
        QDataSet[] dss= new QDataSet[ids.length];
        QDataSet bundle= null;
        try {
            List<QDataSet> dssa= org.autoplot.jythonsupport.Util.getDataSets( Arrays.asList(uris), createProgressMonitor() );
            dss= dssa.toArray( dss );
            if ( dss.length>0 ) {
                dssa= Ops.synchronizeNN( dssa.get(0), dss );
                bundle= Ops.bundle( (QDataSet)dssa.get(0).property(QDataSet.DEPEND_0) );
                for ( int i=0; i<dssa.size(); i++ ) {
                    QDataSet ds1= dssa.get(i);
                    switch (ds1.rank()) {
                        case 1:
                            bundle= Ops.bundle( bundle, dssa.get(i) );
                            break;
                        case 2:
                            for ( int j=0; j<ds1.length(0); j++ ) {
                                bundle= Ops.bundle( bundle, Ops.slice1(ds1,j) );
                            }   break;
                        default:
                            logger.warning("unable to use data, rank is not 1 or 2");
                            break;
                    }    
                }
            }
        } catch (Exception ex) {
            logger.log(Level.SEVERE, null, ex);
        }
        this.bundle= bundle;
    }
        
    QDataSet bundle= null;
    
    /**
     * return the dataset, which is a bundle of URIs, or null.
     * @return 
     */
    public QDataSet getDataSet() {
        if ( bundle==null ) {
            updateDataSet();
        }
        return bundle;
    }
    
    public void setUris( String[] uris ) {
        namedURIListTool1.setUris( Arrays.asList(uris) );
        String[] ids= new String[uris.length];
        for ( int i=0; i<ids.length; i++ ) {
            ids[i]= "ds"+i;
        }
        namedURIListTool1.setIds( Arrays.asList(ids) );
    }
    
    /**
     * @see ScriptContext#formatDataSet(org.das2.qds.QDataSet, java.lang.String) 
     * @return the file name and the arguments
     */
    public String getUri() {
        return exportDataFormatPanel1.getURI();
    }
    
    public void refresh() {
        updateDataSet();
        QDataSet lbundle= getDataSet();
        if ( lbundle==null ) {
            DefaultTableModel n= new DefaultTableModel(1,1);
            n.setValueAt( "No Data", 0, 0 );
            jTable1.setModel( n );
            exportDataFormatPanel1.setDataSet(null);
            exportDataFormatPanel1.setEnabled(true);
            
        } else {
            QDataSetTableModel tm= new QDataSetTableModel(lbundle);
            exportDataFormatPanel1.setDataSet(lbundle);
            exportDataFormatPanel1.setEnabled(true);
            jTable1.setModel(tm);
            jTable1.getTableHeader().addMouseListener( tm.getTableHeaderMouseListener(jTable1) );
        }
    }

    public static void main( String[] args ) {
        ExportDataBundle x= new ExportDataBundle();
        JOptionPane.showMessageDialog( null, x );
        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.autoplot.ExportDataFormatPanel exportDataFormatPanel1;
    private javax.swing.JButton jButton1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private org.autoplot.jythonsupport.ui.NamedURIListTool namedURIListTool1;
    // End of variables declaration//GEN-END:variables
}
