package log.swing;

import log.*;

import util.swing.*;

import java.util.*;

import java.io.*;

/**
  * Swing model for tables that can display log file contents. This model is static and cannot be changed.
  *
  * @see log.LogInputStream
  * @see JLogTable
  * @see DefaultLogEntryTED
  *
  * @author Steffen Zschaler
  * @version 2.0 14/07/1999
  * @since v2.0
  */
public class LogTableModel extends AbstractTableModel {

  /**
    * The LogEntries in the same order in which they appear in the table.
    *
    * @serial
    */
  protected Vector m_vcEntries;

  /**
    * Create a new LogTableModel. Usually you do not create a new model directly, but rather instantiate a
    * new {@link JLogTable}.
    *
    * @param lis the LogInputStream that contains the LogEntries to be displayed. May be filtered.
    * @param cmp a Comparator that defines the order the LogEntries appear in. May be <code>null</code> in
    * which case LogEntries will be sorted by the {@link LogEntry#getLogDate log date}.
    * @param ted a TableEntryDescriptor defining how LogEntries are to be displayed with respect to rows and
    * columns in a table.
    *
    * @see DefaultLogEntryTED
    */
  public LogTableModel (LogInputStream lis,
                        Comparator cmp,
                        TableEntryDescriptor ted) {
    super (ted);

    m_vcEntries = new Vector();

    try {
      while (true) {
        m_vcEntries.addElement (lis.readEntry());
      }
    }
    catch (IOException ioe) {}
    catch (ClassNotFoundException cnfe) {}

    try {
      lis.close();
    }
    catch (IOException ioe) {}

    if (cmp == null) {
      cmp = new Comparator() {
        public int compare (Object o1, Object o2) {
          LogEntry le1 = (LogEntry) o1;
          LogEntry le2 = (LogEntry) o2;

          return le1.getLogDate().compareTo (le2.getLogDate());
        }
      };
    }

    Collections.sort (m_vcEntries, cmp);
  }

  /**
    * Return the LogEntry at row <code>nRow</code>.
    */
  public Object getRecord (int nRow) {
    if ((nRow >=0) &&
        (nRow < m_vcEntries.size())) {
      return m_vcEntries.get (nRow);
    }
    else {
      return null;
    }
  }

  /**
    * Return the total amount of LogEntries in the model.
    */
  public int getRowCount() {
    return m_vcEntries.size();
  }
}