package de.renew.logging.gui;

import java.util.Arrays;

import de.renew.engine.events.SimulationEvent;


/**
 * Represents the simulation events forming a step.
 * Listens to changes in the associated StepTrace.
 * Custom Implementation of a {@link TableModel} to deal with simulation steps.
 * @author Sven Offermann
 */
public class StepTableModel extends TableModel implements StepTraceChangeListener {
    private static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(StepTableModel.class);

    /**
     * The associated StepTrace
     */
    private StepTrace _stepTrace;

    /**
     * The needed RepositoryChangeBuffer
     */
    private RepositoryChangeBuffer _eventBuffer;

    /**
     * Creates new StepTableModel.
     * @param stepTrace the associated StepTrace
     * @param eventBuffer the needed RepositoryChangeBuffer
     */
    public StepTableModel(StepTrace stepTrace, RepositoryChangeBuffer eventBuffer) {
        super(false);

        this._stepTrace = stepTrace;
        this._eventBuffer = eventBuffer;
        eventBuffer.addStepTraceChangeListener(this);
        stepTrace.addStepTraceChangeListener(eventBuffer);

        SimulationEvent[] messages = stepTrace.getEvents();
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace(
                StepTableModel.class.getSimpleName() + ": Initially including " + messages.length
                    + " events for " + stepTrace + ".\n" + Arrays.toString(messages));
        }
        for (int x = 0; x < messages.length; x++) {
            addRow(new Object[] { messages[x] });
        }
    }

    @Override
    public void stepTraceChanged(StepTrace stepTrace) {
        if (stepTrace == this._stepTrace) {
            // add new trace message to table model
            SimulationEvent[] messages = stepTrace.getEvents();
            for (int x = getRowCount(); x < messages.length; x++) {
                addRow(new Object[] { messages[x] });
            }
            fireTableRowsInserted(getRowCount() - messages.length - 1, getRowCount() - 1);
        }
    }

    /**
     * Removes all listeners and their references
     */
    public void dispose() {
        _stepTrace.removeStepTraceChangeListener(_eventBuffer);
        _eventBuffer.removeStepTraceChangeListener(this);
    }
}