package com.l2fprod.tools;

import java.awt.*;
import java.awt.image.*;
import java.io.File;

import javax.swing.ImageIcon;

import javax.imageio.*;

public class ImageUtils {

  public static Component bitmapCreator = new javax.swing.JLabel();
  

  public static Image loadPng(String pathToImage) throws Exception {
    ImageIcon icon = new ImageIcon(new File(pathToImage).toURL());
    return icon.getImage();
  }

  public static void savePng(Image image, String pathToImage) throws Exception {
    ImageIO.write((RenderedImage)image, "png", new File(pathToImage));
  }

  private static String getFileFmt(String pathToImage) throws Exception {
    String fmt;
    if (pathToImage.toLowerCase().endsWith(".png")) {
      return "png";
    }
    if (pathToImage.toLowerCase().endsWith(".gif")) {
      return "gif";
    }
    if (pathToImage.toLowerCase().endsWith(".bmp")) {
      return "bmp";
    }
    return "";
  }
  
  public static void createPicture(String pathToImage, int index, int maxParts,
                                   String filename, boolean horizontal) {
    try {
      System.out.println("working with " + pathToImage);
      Image image = null;
      image = Toolkit.getDefaultToolkit().getImage(pathToImage);

      // if only one image, dump it as it
      if (index == 0 && maxParts == 1) {
        ImageIO.write((RenderedImage)image, getFileFmt(pathToImage), new File(pathToImage));
      } else {
        if (horizontal) {
          int partHeight = image.getHeight(bitmapCreator) / maxParts;
          image = grab(image, 0, partHeight*index, 
                       image.getWidth(bitmapCreator), partHeight);
        } else {
          int partWidth = image.getWidth(bitmapCreator) / maxParts;
          image = grab(image, partWidth * index, 0,
                       partWidth, image.getHeight(bitmapCreator));
        }
	ImageIO.write((RenderedImage)image, getFileFmt(pathToImage), new File(pathToImage));
      }
    } catch (Exception e) {
      System.out.println("error while working with " + pathToImage);
	    e.printStackTrace();
    }
  }
  
  public static Image grab(Image image, int x, int y, int width, int height) {
    if (width * height < 0)
	    return null;
    
    int[] pixels = new int[width * height];
    PixelGrabber grabber = new PixelGrabber(image, x, y, width, height, pixels, 0, width);
    try {
	    grabber.grabPixels();
    } catch (Exception e) {
	    e.printStackTrace();
    }
    return bitmapCreator.createImage(new MemoryImageSource(width, height, pixels, 0, width));
  }

}
