/*
 *
 *  Copyright (C) 1999, Institute for MicroTherapy
 *
 *  This software and supporting documentation were developed by
 *
 *    University of Witten/Herdecke
 *    Department of Radiology and MicroTherapy
 *    Institute for MicroTherapy
 *    Medical computer science
 *    
 *    Universitaetsstrasse 142
 *    44799 Bochum, Germany
 *    
 *    http://www.microtherapy.de/go/cs
 *    mailto:computer.science@microtherapy.de
 *
 *  THIS SOFTWARE IS MADE AVAILABLE,  AS IS,  AND THE INSTITUTE MAKES  NO 
 *  WARRANTY REGARDING THE SOFTWARE, ITS PERFORMANCE, ITS MERCHANTABILITY
 *  OR FITNESS FOR ANY PARTICULAR USE, FREEDOM FROM ANY COMPUTER DISEASES 
 *  OR ITS CONFORMITY TO ANY SPECIFICATION. THE ENTIRE RISK AS TO QUALITY 
 *  AND PERFORMANCE OF THE SOFTWARE IS WITH THE USER.
 *
 *  Author :      $Author: kleber $
 *  Last update : $Date: 2001/06/06 10:32:30 $
 *  Revision :    $Revision: 1.1.1.1 $
 *  State:        $State: Exp $
*/


package processCommunication;

import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.text.*;

/**
*
*/ 
public final class ProcessTable extends JTable 
{
    private TableData tableData; // die Tabellendaten
    
    private JTextArea textArea;
    private boolean sortUp = false;
    Object[] columnIdentifiers = {"Status","Process Type","Process Id","Date","Message Type","Text"};
    // Konstruktion des Tabellen-Dialogs
    public ProcessTable(JTextArea textArea, Vector messageList, java.awt.Font f)
    {
        super();
        this.textArea =textArea;
        textArea.setFont(f);
        //init model 
        tableData = new TableData(columnIdentifiers); 
        setModel(tableData); // Konstruktion der sichtbaren Tabelle
        // init table
        getColumnModel().removeColumn(getColumn("Text"));
	getColumnModel ().getColumn (0).setPreferredWidth (80);
	getColumnModel ().getColumn (1).setPreferredWidth (80);
	getColumnModel ().getColumn (2).setPreferredWidth (80);
	getColumnModel ().getColumn (3).setPreferredWidth (200);
	setAutoResizeMode (AUTO_RESIZE_LAST_COLUMN);
	
        
        // init selection 
        setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // immer nur eine Zeile auswählbar
        getSelectionModel().addListSelectionListener(new SelectRowListener(textArea));
        
        // init Mouse Listener
        getTableHeader().addMouseListener(new TableMouseListener()); // Mausaktion im Header abfangen
        
        
       
    }
    /**
    * Sort the table.
    * @param index Specifies the colum to be sorted
    */ 
    private void sort (int index)
    {
            if (sortUp)
            {// Bubblesort
                for(int i = 0; i < tableData.getRowCount(); i++)
                {
                    for(int j = i + 1; j < tableData.getRowCount(); j++)
                    {
                        if (tableData.compareTo(index, i, j) > 0)
                        {
                            tableData.swapRows(i, j);
                        }
                    }
                }
                sortUp = false;
            }
             else
             {
                for(int i = 0; i < tableData.getRowCount(); i++)
                {
                    for(int j = i + 1; j < tableData.getRowCount(); j++)
                    {
                        if (tableData.compareTo(index, i, j) < 0)
                        {
                            tableData.swapRows(i, j);
                        }
                    }
                }
                sortUp = true;
                
             }
            repaint(); // Tabelle neuzeichnen
        
    }
    /**
    * Inserts the specified DicomScopeMessage as a row
    */
    public  void insertData(DicomScopeMessage m)
    {
        Object[]  o = {m.statusName,m.processTypeName,new Integer(m.processId),m.date,m.messageName,m.text};
        tableData.addRow(o);
    }
    /**
    * Deletes all Rows
    */ 
    public void deleteAll()
    {
        tableData.setRowCount(0);
    }
    
    /**
    * This class extends the DefaultTableModel do that the needed
    * columnIdentifiers
    * 
    */ 
    private class TableData extends DefaultTableModel
    {
        
        int[][] sortMatrix = {
            { 3, 2, 3, 3, 3 },  /* second column: second sort criterion */
            { 3, 3, 3, 3, 3 }   /* third column: third sort criterion */
        };
        
        /**
        * Checks if row1< row2. The type of comparison is defined by cols.
        * @return 0 if equals, -1 if row1 < row2, 1 if row1>row2.
        */
        public int compareTo(int col, int row1, int row2)
        {
            int secondCriterion=sortMatrix[0][col];
            int thirdCriterion=sortMatrix[1][col];
            
            int result = ((Comparable)tableData.getValueAt(row1, col)).compareTo((tableData.getValueAt(row2, col)));
            if (result == 0) result = ((Comparable)tableData.getValueAt(row1, secondCriterion)).compareTo((tableData.getValueAt(row2, secondCriterion)));
            if (result == 0) result = ((Comparable)tableData.getValueAt(row1, thirdCriterion)).compareTo((tableData.getValueAt(row2, thirdCriterion)));
            return result;            
        }
        
        /**
        * Constructor. Sets the colum identifiers.
        * @param columnIdentifiers column identifiers
        */
        public TableData(Object[] columnIdentifiers)
        {
            super(columnIdentifiers,0);
        }
        
        /**
        * Sets an editable
        */
        public boolean isCellEditable(int row, int cols)
        {
            return false;
        }
        
        /**
        * Returns the index of the invislibe cols
        */
        public int[] getInvisibleColumns()
        {
            
            //Number of cols in the model
            int cols = getColumnCount(); // Anzahl der Spalten merken
            
            //init array with size of invisible cols
            //( cols of the modle - cols of the table
            int[] invisible = new int[cols - getColumnCount()];
            
            //Fills array
            for(int i = 0, j = 0; i < cols; i++) // 
            {
                if(convertColumnIndexToView(i) < 0) 
                {
                    invisible[j++] = i; 
                }
            }
            return invisible; 
        }
      
        public void setRowCount(int index)
        {
            super.setRowCount(index);
        }
        
        /**
        * Swaps the rows.
        * @param row1 First row
        * @param row2 Secound row
        */
        public void swapRows(int row1, int row2)
        {
            Object dummy = dataVector.elementAt(row1);
            dataVector.setElementAt(dataVector.elementAt(row2), row1);
            dataVector.setElementAt(dummy, row2);
        }
    }
    
    /**
    * Testet auf Klicks in den Tabellenheader
    */
    private class TableMouseListener extends MouseAdapter
        
    {
        public void mouseClicked(MouseEvent e)
        {
            
            if(SwingUtilities.isRightMouseButton(e)) // nur mit der rechten Maustaste zulassen
            {
                TableColumnModel tcm = getTableHeader().getColumnModel(); // schon mal das Spaltenmodell holen
                int index = tcm.getColumnIndexAtX(e.getX()); // Index der angeklickten Spalte ermitteln

                if(index >= 0) // wurde tatsächlich eine Spalte angeklickt...
                {
                    int modelIndex = convertColumnIndexToModel(index); // ...hole Spaltenindex des Modells
                    
                    sort(modelIndex); 
                }
            }
        }
    }
        
        
        
    
    /**
    * This class listens for the selelction of rows and set the 
    * text of the specified row (which presents a DicomScopeMessage)
    * to a TextField
    */
    private  class SelectRowListener implements ListSelectionListener
    {
        /**
        * Displays the text
        */
        private JTextComponent textField;
        /**
        * Constructor
        */
        public SelectRowListener(JTextComponent textField)
        {
            this.textField = textField;
        }
        public void valueChanged(ListSelectionEvent e)
        {
            if (e == null) return;
            int index = getSelectedRow();            
            if (index != -1&& e.getValueIsAdjusting())
            {
                textField.setText((String)tableData.getValueAt(index, tableData. getColumnCount()-1));
                textField.select(0,0);
            }
            
        }
   }
   
    
}
/*
 *  CVS Log
 *  $Log: ProcessTable.java,v $
 *  Revision 1.1.1.1  2001/06/06 10:32:30  kleber
 *  Init commit for DICOMscope 3.5
 *  Create new CVS
 *
*/
