package scone.thumbnailgenerator;


import horst.HTMLPane;
import horst.HTMLWindow;

import java.awt.Frame;
import java.awt.Image;
import java.net.URL;

import scone.netobjects.SimpleUri;


/**
 * This thumbnail-generator provides functionality to get a thumbnail-image of the contents displayed under a given URL.
 * It uses the java web-browser package HTMLWindow (http://home.earthlink.net/~hheister/) written by Horst Heistermann.
 *
 * @author Frank Wollenweber
 */

public class ThumbnailGenerator {

    private static HTMLWindow hw = new HTMLWindow(); // Only one!! Otherwise there are memory problems...
    private static HTMLPane hp = hw.getHTMLPane();  // This is used to render the document
    private Image img; // The image of the document
    private Image thumbnail; // The thumbnail of the image

    /**
     * constructor
     */
    public ThumbnailGenerator() {}

    /**
     * Generates a thumbnail of the document displayed at the specified URI
     * @param sUri get a thumbnail from this document
     */
    public void generateThumbnail(SimpleUri sUri) {
        generateThumbnail(sUri.toURL());
    }

    /**
     * Generates a thumbnail of the document displayed at the specified URL
     * @param url get a thumbnail from this document
     */
    public void generateThumbnail(URL url) {
        synchronized (hp) {
            hp.setProgressiveDisplay(false);
            try {
                hp.syncOpenPage(url);
            } catch (Exception e) {
                System.out.println(e);
            }
            Frame f = new Frame();

            f.addNotify();
            f.add(hw);
            try {
                img = hp.getPageImage(1, 800, 600);
                thumbnail = img.getScaledInstance(-1, 110, 4);
            } catch (Exception e) {
                System.out.println("No thumbnail available for " + url);
            }
        }
    }

    /**
     * Get the thumbnail
     * @return thumbnail-image of the current document
     */
    public Image getThumbnail() {
        return thumbnail;
    }

    /**
     * Get the document's full-sized image
     * @return image of the current document
     */
    public Image getImage() {
        return img;
    }

    /**
     * Flushes all resources being used by the image and the thumbnail
     */
    public void flush() {
        try {
            img.flush();
            thumbnail.flush();
        } catch (NullPointerException e) {}
    }
}
