/*
 * Licensed Materials - Property of Rogue Wave Software, Inc. 
 * © Copyright Rogue Wave Software, Inc. 2014, 2016 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */

import java.awt.Dimension;

import ilog.views.IlvManagerView;
import ilog.views.IlvRect;
import ilog.views.IlvTransformer;
import ilog.views.tiling.IlvTileController;
import ilog.views.tiling.IlvTileLockFilter;

/**
 * A tile lock filter that does not allow more than N tiles to be loaded
 */
class TileFilter extends IlvTileLockFilter {
  /**
   * Internally stores the maximum number of tiles that can be locked
   */
  private int maxTileNum;

  /**
   * Constructs a new TileFilter to not lock more than specified number of tiles
   * 
   * @param maxTile
   *          maximum number of tiles that can be locked
   */
  public TileFilter(int maxTile) {
    super();
    maxTileNum = maxTile;
  }

  public boolean isLockAllowed(IlvTileController tileController, IlvManagerView view) {
    // get the size of the view
    Dimension size = view.getSize();

    // compute the corners of the view in the manager coordinate system
    IlvTransformer t = view.getTransformer();
    if (t == null)
      return true;
    IlvRect rect = new IlvRect(0, 0, size.width, size.height);
    t.inverse(rect);

    // compute the number of visible tiles
    int indexes[] = tileController.getTileIndexes(rect);
    int horizontalTiles = indexes[IlvTileController.RIGHT_COLUMN_INDEX] - indexes[IlvTileController.LEFT_COLUMN_INDEX]
        + 1;
    int verticalTiles = indexes[IlvTileController.LOWER_ROW_INDEX] - indexes[IlvTileController.UPPER_ROW_INDEX] + 1;
    if ((horizontalTiles * verticalTiles) > maxTileNum)
      return false;
    else
      return true;
  }

  public boolean isPersistent() {
    return false;
  }
}