/*
 * 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.
 */
package jp.sourceforge.dvibrowser.dvicore.image.split;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;

import jp.sourceforge.dvibrowser.dvicore.DviException;
import jp.sourceforge.dvibrowser.dvicore.DviRect;
import jp.sourceforge.dvibrowser.dvicore.DviSize;


public class SplitImageUtils {
  public static void renderToGraphics(Graphics g, SplitImage img, int x, int y, double scale) throws DviException
  {
    if (g == null) throw new NullPointerException("Graphics object can't be null");
    if (img == null) throw new NullPointerException("img can't be null");
    
    Graphics2D gg = (Graphics2D) g;
    
    DviSize unit = img.getRectSplitter().getUnitSize();
    DviSize scaleUnit = unit.magnify(scale);
    DviRect clip = DviRect.fromRectangle(g.getClipBounds());
    
    for (SplitPiece piece : img) {
      int row = piece.getRow();
      int col = piece.getColumn();
      DviRect scaledRect = piece.getRect().magnify(scale).moveTo(x + col * scaleUnit.width, y + row * scaleUnit.height);
      if (clip != null && !scaledRect.intersects(clip)) continue;
      Rectangle r = scaledRect.toRectangle();
      Image img2 = piece.getImage();
      gg.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
          RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      gg.drawImage(piece.getImage(), r.x, r.y, r.x + r.width + 1, r.y + r.height + 1, 0, 0, img2.getWidth(null), img2.getHeight(null), null);
    }
  }
}
