/*
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 


//  JayTable.java requires no other files.
//  Modified by Dayle Kotturi <dayle@slac.stanford.edu> September 2010 

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

// 21jul2010 New, in order to write selected "row" to the RULEx_ID PV
import gov.sns.ca.Channel;
import gov.sns.ca.ChannelException;
import gov.sns.ca.ChannelFactory;
import gov.sns.ca.ConnectionException;
import gov.sns.ca.GetException;
import gov.sns.ca.PutException;

public class JayTable extends JPanel {
    private static boolean DEBUG = false;
    // 2010 10 25 New that it's here, that it's private and that it's static: 
    private static JTable myTable = null;
    int ii;

    // Constructor. 2010 10 25 Now called from main. 
    // Constructor calls its own private static "initialize" method to do the work
    public JayTable(final String[] listOfNames, String tableTitle, final int[] validRuleIndices, final int numValidRules, final Channel[] ruleIDChan, String pvName) {
        super(new GridLayout(1,0));  // this line must be first statement in the constructor. don't agree? try moving it below

        if (DEBUG) {
            System.out.println("JayTable constructor");
            for (ii=0; ii< listOfNames.length; ii++) { 
                System.out.println("Global Rule Names are "+listOfNames[ii]);
            }
        }

        initialize(listOfNames, tableTitle, pvName, numValidRules);

        myTable.addMouseListener(new MouseAdapter() {
          public void mouseClicked(MouseEvent me) {
            if (DEBUG) { 
              printDebugData(myTable);
            }

            // Get the selected row:
            int row;
            int rule;
            row = myTable.getSelectionModel().getLeadSelectionIndex();
            rule = validRuleIndices[row];
            if (DEBUG) {
              System.out.println("selected row:"+row+". This maps to rule: "+rule);
            }

            // Set row to value of destTriggerRule PV via jca
            try {
              updatePv(ruleIDChan, rule);
              System.exit(0);
            } catch (ConnectionException e) {
            	e.printStackTrace();
            }
          }
        });

    }
 
    private void updatePv(Channel[] ruleIDChan, int ruleID) throws ConnectionException {
      // Set row to value of destTrigger PV via jca
      try {
        ruleIDChan[0].putVal(ruleID);
        // Get their choice and exit. Somewhat harsh, but one fewer click this way
        System.exit(0);
      } catch (ConnectionException e) {
        System.err.println("Caught connection exception");
        e.printStackTrace();
      } catch (PutException e) {
        System.err.println("Caught put exception");
        e.printStackTrace();
      } catch (Exception e) {
        System.err.println("Caught exception");
        e.printStackTrace();
      }
    }

    private void printDebugData(JTable table) {
        int numRows = table.getRowCount();
        int numCols = table.getColumnCount();
        javax.swing.table.TableModel model = table.getModel();

        System.out.println("Value of data: ");
        for (int i=0; i < numRows; i++) {
            System.out.print("    row " + i + ":");
            for (int j=0; j < numCols; j++) {
                System.out.print("  " + model.getValueAt(i, j));
            }
            System.out.println();
        }
    }

    // Create the GUI and show it.  
    // For thread safety, this method should be invoked from the event-dispatching thread.
    private void initialize(String[] listOfNames, String tableTitle, String pvName, int numValidRules) { 
        int numGlobalRules;
        int ii;
  
        // Ideally, this frame's handle would be obtained and passed to edm for drawing this as an embedded window
        // Actually, this was not obtainable and so the frame is haphazardly and disjointly drawn on the screen.
        //int winid;
        //winid = (int) XtWindow(frame); needs symbol

        if (DEBUG) {
            System.out.println("Drawing table called "+tableTitle);
            System.out.println("to set PV: "+pvName);
            for (ii=0; ii< listOfNames.length; ii++) { 
                System.out.println("Choices are "+listOfNames[ii]);
            }
        }

        // Create the table model to hold the list of global rules
        JayTableModel model = new JayTableModel(listOfNames, tableTitle, numValidRules);
        myTable = new JTable(model);

        // This must come RIGHT after the table is created. 
        // Create the scroll pane and add the table to it.
        JScrollPane scrollPane = new JScrollPane(myTable);

        //Add the scroll pane to this panel.
        add(scrollPane);

        numGlobalRules = myTable.getRowCount();
        if (DEBUG) {System.out.println(numGlobalRules+" global rules");}
        int tableHeight = 15 + (myTable.getRowCount()) * 15;

        myTable.setPreferredScrollableViewportSize(new Dimension(300, tableHeight));
        myTable.setOpaque(true); //content panes must be opaque

    }
}
