/*----------------------------------------------------------------------------
Copyright (c)2000 TogetherSoft Corporation. Patents pending. All rights reserved.
----------------------------------------------------------------------------*/

package com.togethersoft.modules.inspector.customproperties;

import com.togethersoft.openapi.ide.IdeAccess;
import com.togethersoft.openapi.ide.inspector.IdeInspectorPropertySetComponent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

public abstract class IdeInspectorPropertySetAddButton extends JButton implements ActionListener {
  public IdeInspectorPropertySetAddButton(String title, JTable table, IdeInspectorPropertySetComponent component) {
    super(title);
    myTable = table;
    myComponent = component;
    addActionListener(this);
  }

  public void actionPerformed(ActionEvent e) {
    ListSelectionModel sel = myTable.getSelectionModel();
    if(myTable.isEditing()) {
      myTable.getCellEditor(myTable.getEditingRow(), myTable.getEditingColumn()).cancelCellEditing();
    }
    IdeAccess.getIdeManager().addCommandToQueue(new Runnable() {
      public void run() {
        doAdd();
      }
    }, "Created a new element ");
  }

  protected void selectRow(final int row) {
    final ListSelectionModel sel = myTable.getSelectionModel();
    if (row != -1) {
      SwingUtilities.invokeLater(new Runnable(){
        public void run() {
          sel.setSelectionInterval(row, row);
        }
      });
    } else {
      throw new IllegalArgumentException("Could not select row == -1");
    }
  }

  protected void startEditing(final int row, final int column) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        myTable.getColumnModel().getSelectionModel().setSelectionInterval(column, column);
        myTable.requestFocus();
        myTable.editCellAt(row, column);
      }
    });
  }

  protected abstract void doAdd();

  protected JTable myTable;
  protected IdeInspectorPropertySetComponent myComponent;
}
