package com.dlsc.flexgantt.showcase.demo.relationships;

import java.util.Comparator;

import com.dlsc.flexgantt.model.gantt.TimelineObjectPath;
import com.dlsc.flexgantt.model.scheduling.ConstraintViolationMessage;
import com.dlsc.flexgantt.swing.MessageTable;
import com.dlsc.flexgantt.swing.treetable.TreeTable;


/**
 * Sorts constraint violation messages based on the rows where the source timeline objects of the
 * two violations are located. Using this comparator for sorting makes it possible to display the
 * messages in the {@link MessageTable} in the order of their occurence in the Gantt chart.
 * 
 * @since 2.1
 * @author Dirk Lemmermann
 */
public class ConstraintViolationMessageComparator implements Comparator<ConstraintViolationMessage> {

  private TreeTable treeTable;

  /**
   * Constructs a new comparator, which will be based on the given tree table.
   * 
   * @param treeTable the tree table used for looking up the row indices for the sorted constraint
   * violation messages
   */
  public ConstraintViolationMessageComparator(TreeTable treeTable) {
    if (treeTable == null) {
      throw new IllegalArgumentException("tree table can not be null");
    }
    this.treeTable = treeTable;
  }

  /** {@inheritDoc} */
  @Override
  public int compare(ConstraintViolationMessage m1, ConstraintViolationMessage m2) {
    TimelineObjectPath<?> path1 = m1.getConstraint().getSourcePath();
    TimelineObjectPath<?> path2 = m2.getConstraint().getSourcePath();
    int row1 = treeTable.getRowForPath(path1);
    int row2 = treeTable.getRowForPath(path2);
    return row1 - row2;
  }
}
