package eu.gity.jmeter.ddos.stairsddosthreadgrp.gui;

import org.apache.jmeter.gui.util.PowerTableModel;

import javax.swing.*;
import javax.swing.table.TableCellEditor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DeleteRowAction
        implements ActionListener {

    private final JComponent sender;
    private final JTable grid;
    private final PowerTableModel tableModel;
    private final JButton deleteRowButton;

    public DeleteRowAction(JComponent aSender, JTable grid, PowerTableModel tableModel, JButton deleteRowButton) {
        this.grid = grid;
        this.tableModel = tableModel;
        this.deleteRowButton = deleteRowButton;
        this.sender = aSender;
    }

    public void actionPerformed(ActionEvent e) {
        if (grid.isEditing()) {
            TableCellEditor cellEditor = grid.getCellEditor(grid.getEditingRow(), grid.getEditingColumn());
            cellEditor.cancelCellEditing();
        }

        int rowSelected = grid.getSelectedRow();
        if (rowSelected >= 0) {
            tableModel.removeRow(rowSelected);
            tableModel.fireTableDataChanged();

            // Disable DELETE if there are no rows in the table to delete.
            if (tableModel.getRowCount() == 0) {
                deleteRowButton.setEnabled(false);
            } // Table still contains one or more rows, so highlight (select)
            // the appropriate one.
            else {
                int rowToSelect = rowSelected;

                if (rowSelected >= tableModel.getRowCount()) {
                    rowToSelect = rowSelected - 1;
                }

                grid.setRowSelectionInterval(rowToSelect, rowToSelect);
            }
            sender.updateUI();
        }
    }
}
