package com.neilmoomey.jpegbrowser2;



import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.util.*;

import java.net.*;

import com.neilmoomey.util.Type;



/** ImagePane.java

 * @author Neil Moomey, www.neilmoomey.com

 * @version 1.0

 **/



public class ImagePane extends JLabel {

	private ImageIcon imageIcon;

	private Image image, imageResized;

	MediaTracker imageTracker;

	private int imageWidth, imageHeight;



	public ImagePane(String name) {

		imageTracker = new MediaTracker(this);

		name=name.replace('\\','/');

		image = Toolkit.getDefaultToolkit().getImage(name);

		imageTracker.addImage(image,0);

		try {

			imageTracker.waitForID(0);

		} catch (InterruptedException e1) {

		}

		//int filesize = image.getFileSize();

		int width = image.getWidth(null);

		int height = image.getHeight(null);

		setImageWidth(width);

		setImageHeight(height);

		System.out.println("Original width = "+width+" height = "+height);

		float tempWidth = Type.toFloat(width);

		float tempHeight = Type.toFloat(height);

		int w =java.awt.Toolkit.getDefaultToolkit().getScreenSize().width;

		int h =java.awt.Toolkit.getDefaultToolkit().getScreenSize().height;

		float maxWidth=w-225-22; //780;

		float maxHeight=h-52; //710;

		imageIcon = new ImageIcon(image);

		if (width*height != 0) {

			if (tempWidth > maxWidth) {

				tempHeight = (maxWidth/tempWidth)*tempHeight;

				tempWidth=maxWidth;

				width = Type.toInt(tempWidth);

				height = Type.toInt(tempHeight);

				imageResized = image.getScaledInstance(width, height,0);

				imageIcon = new ImageIcon(imageResized);

			}



			if (tempHeight > maxHeight) {

				tempWidth = (maxHeight/tempHeight)*tempWidth;

				tempHeight=maxHeight;

				width = Type.toInt(tempWidth);

				height = Type.toInt(tempHeight);

				imageResized = image.getScaledInstance(width, height,0);

				imageIcon = new ImageIcon(imageResized);

			}

		}



		System.out.println("Final width = "+width+" height = "+height);



		setIcon(imageIcon);

	}



	public int getImageWidth() {

		return this.imageWidth;

	}



	public void setImageWidth(int width) {

		this.imageWidth = width;

	}



	public int getImageHeight() {

		return this.imageHeight;

	}

	public void setImageHeight(int height) {

		this.imageHeight = height;

	}

/*

	public int getFileSize() {

		return this.fileSize;

	}



	public void setFileSize(int filesize) {

		this.fileSize = filesize;

	}

*/

	public static void main(String[] args) {

		ImagePane imagePane = new ImagePane("icon.png");

		JFrame f = new JFrame("Image Pane Test");

		f.getContentPane().add(imagePane);

		f.setSize(900, 700);

		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		f.setVisible(true);



	}

}

