package jp.sourceforge.dvibrowser.dvicore;

/*
 * Copyright (c) 2009, Takeyuki Nagao
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the
 * following conditions are met:
 * 
 *  * Redistributions of source code must retain the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer.
 *  * Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the
 *    following disclaimer in the documentation and/or other
 *    materials provided with the distribution.
 *    
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 */

public class DviRectSplitter {
  private final DviRect rect;
  private final DviSize unit;
  private final int cols;
  private final int rows;

  public DviRectSplitter(DviRect rect, DviSize unit)
  {
    this.rect = rect;
    this.unit = unit;
    
    if (unit.width == 0) throw new IllegalArgumentException("width must be > 0: " + unit.width);
    if (unit.height == 0) throw new IllegalArgumentException("height must be > 0: " + unit.height);
    this.cols = (rect.width() + unit.width - 1) / unit.width;
    this.rows = (rect.height() + unit.height - 1) / unit.height;
  }
  
  public int getNumColumns()
  {
    return cols;
  }
  
  public int getNumRows()
  {
    return rows;
  }
  
  public DviRect getRect() { return rect; }
  public DviSize getUnitSize() { return unit; }
  
  public DviRect getRectAt(int row, int col)
  {
    if (row < 0 || rows <= row)
      throw new IllegalArgumentException("Row index out of range: " + row);
    if (col < 0 || cols <= col)
      throw new IllegalArgumentException("Column index out of range: " + col);
    int x = rect.x() + col * unit.width();
    int y = rect.y() + row * unit.height();
    DviRect r = new DviRect(x, y, unit);
    
    return r.intersect(rect);
  }
  
  public DviRect [][] getRects()
  {
    DviRect [] [] rects = new DviRect[rows][cols];
    for (int i=0; i<rows; i++) {
      for (int j=0; j<cols; j++) {
        rects[i][j] = getRectAt(i, j);
      }
    }
    return rects;
  }
}
