/*
 * @(#)Main.java  1.0  2011-08-15
 * 
 * Copyright (c) 2011 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 * 
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */
package org.monte.cmykdemo;

import java.awt.Image;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.SwingWorker;
import javax.swing.TransferHandler;

/**
 * Main.
 *
 * @author Werner Randelshofer
 * @version 1.0 2011-08-15 Created.
 */
public class Main extends javax.swing.JFrame {

    private Handler handler;

    /** Creates new form Main */
    public Main() {
        initComponents();
        setSize(400, 300);

        handler = new Handler();
        setTransferHandler(handler);
        imageLabel.setTransferHandler(handler);
        scrollPane.setTransferHandler(handler);
        scrollPane.getViewport().setTransferHandler(handler);
    }

    /** This method asynchronously loads an image file. */
    public void setFile(final File file) {
        imageLabel.setIcon(null);
        imageLabel.setText("Loading image...");

        new SwingWorker<Image, Image>() {

            @Override
            protected Image doInBackground() throws Exception {
                // Loads a JPEG image using the Java ImageIO API
                // ---------------------------------------------
                
                // The ImageIO API may provide many ImageReaders which
                // claim to be able to read the file. We try them all
                // out until we succeed.
                
                Image img = null;
                ImageInputStream iis = new FileImageInputStream(file);
                try {
                    for (Iterator<ImageReader> i = ImageIO.getImageReaders(iis); img == null && i.hasNext();) {
                        ImageReader r = i.next();
                        try {
                            r.setInput(iis);
                            img = r.read(0);
                        } catch (IOException e) {
                        }
                    }
                } finally {
                    iis.close();
                }
                return img;
            }

            @Override
            protected void done() {
                // Show the image or apologize in case of failure
                // -----------------------------------------------
                try {
                    Image image = get();
                    if (image == null) {
                        imageLabel.setText("Sorry. Couldn't load image.");
                    } else {
                        imageLabel.setText(null);
                        imageLabel.setIcon(new ImageIcon(image));
                    }
                } catch (Exception ex) {
                    imageLabel.setText("Sorry. Couldn't load image.");
                    ex.printStackTrace();
                }
                super.done();
            }
        }.execute();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollPane = new javax.swing.JScrollPane();
        imageLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("CMYK Demo © Werner Randelshofer");

        scrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));

        imageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imageLabel.setText("Drop CMYK image here");
        scrollPane.setViewportView(imageLabel);

        getContentPane().add(scrollPane, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel imageLabel;
    private javax.swing.JScrollPane scrollPane;
    // End of variables declaration//GEN-END:variables

    /** Transfer handler for drag and drop functionality. */
    private class Handler extends TransferHandler {

        @Override
        public boolean canImport(TransferSupport support) {
            return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
        }

        @Override
        public boolean importData(TransferSupport support) {
            try {
                List<File> files = (List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                if (files.size() == 1) {
                    setFile(files.get(0));
                }
                return true;
            } catch (UnsupportedFlavorException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return false;
        }
    }
}
