// ============================================================================
// File:               $File$
//
// Project:            Useful tools.
//
// Purpose:            User interface to convert a file location to an URL.
//
// Author:             Rammi (rammi [AT] caff.de)
//
// Copyright Notice:   This code is in the public domain.
//
//
// Legal Notice:       No guarantees given.
//
// Latest change:      $Date$
//
// History:	       $Log$
//=============================================================================

import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.net.MalformedURLException;

/**
 *  Because I always forget how to do the URL for files.
 *  @author Rammi (rammi [AT] caff.de)
 *  @version $Revision$
 */
public class File2URL
        extends JFrame
{
  private JTextField inputField;
  private JLabel     outputLabel;
  private Color      standardColor;
  private Color      errorColor;

  /**
   * Creates a new, initially invisible <code>Frame</code> with the
   * specified title.
   * <p>
   * This constructor sets the component's locale property to the value
   * returned by <code>JComponent.getDefaultLocale</code>.
   *
   * @exception HeadlessException if GraphicsEnvironment.isHeadless()
   * returns true.
   * @see GraphicsEnvironment#isHeadless
   * @see Component#setSize
   * @see Component#setVisible
   * @see JComponent#getDefaultLocale
   */
  public File2URL()
  {
    super("File to URL");
    Container pane = getContentPane();

    GridBagLayout gbl = new GridBagLayout();
    pane.setLayout(gbl);
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.insets = new Insets(3, 5, 3, 5);
    gbc.fill   = GridBagConstraints.NONE;
    gbc.anchor = GridBagConstraints.WEST;
    gbc.weightx = 1;
    gbc.weighty = 1;

    JLabel label = new JLabel("Print file name:");
    gbl.setConstraints(label, gbc);
    pane.add(label);

    inputField = new JTextField(60);
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbl.setConstraints(inputField, gbc);
    pane.add(inputField);

    JButton dialogButton = new JButton("Show file dialog");
    //gbc.fill = GridBagConstraints.NONE;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbl.setConstraints(dialogButton, gbc);
    pane.add(dialogButton);

    label = new JLabel("URL:");
    gbc.gridwidth = 1;
    gbc.fill   = GridBagConstraints.NONE;
    gbl.setConstraints(label, gbc);
    pane.add(label);

    outputLabel = new JLabel(" ");
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbl.setConstraints(outputLabel, gbc);
    pane.add(outputLabel);

    JButton copyButton = new JButton("Copy URL to clipboard");
    //gbc.fill = GridBagConstraints.NONE;
    gbc.gridwidth = GridBagConstraints.REMAINDER;
    gbl.setConstraints(copyButton, gbc);
    pane.add(copyButton);

    standardColor = outputLabel.getForeground();
    errorColor = Color.red.darker();

    inputField.addCaretListener(new CaretListener() {
      /**
       * Called when the caret position is updated.
       *
       * @param e the caret event
       */
      public void caretUpdate(CaretEvent e)
      {
        updateURL();
      }
    });

    dialogButton.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        JFileChooser fc;
        String text = inputField.getText();
        File   file = new File(text);
        File   path = file.isDirectory() ? file : file.getParentFile();

        fc = (path != null  &&   path.exists())  ?  new JFileChooser(path)  :  new JFileChooser();

	fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        int returnVal = fc.showOpenDialog(File2URL.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
          inputField.setText(fc.getSelectedFile().getPath());
          updateURL();
        }
      }
    });

    copyButton.addActionListener(new ActionListener() 
    {
      public void actionPerformed(ActionEvent e)
      {
	 Clipboard clipboard = getToolkit().getSystemClipboard();
        try {
          clipboard.setContents(new StringSelection(outputLabel.getText()),
                                new ClipboardOwner()
                                {
                                  public void lostOwnership(Clipboard clipboard, Transferable contents)
                                  {
                                    // don't care
                                  }
                                });
        } catch (Exception e1) {
          JOptionPane.showConfirmDialog(File2URL.this, "Error copying to clipboard: "+e1.getMessage(),
                                        "Error", JOptionPane.ERROR);
        }
      }
    });


    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e)
      {
        System.exit(0);
      }
    });

    pack();

    updateURL();
  }

  private void updateURL()
  {
    String input = inputField.getText();

    try {
      String output =  new File(input).toURL().toString();
      outputLabel.setForeground(standardColor);
      if (output.length() > 0) {
        outputLabel.setText(output);
      }
      else {
        outputLabel.setText(" ");
      }
    } catch (MalformedURLException x) {
      outputLabel.setForeground(errorColor);
      outputLabel.setText("Cannot convert to URL");
    }
  }

  /**
   *  Main method. If called with arguments, interprete them as filenames and
   *  shows matching URLs. If called with no arguments, pop up a window which allows
   *  input of a filename and shows matching URL.
   *  @param args arguments
   */
  public static void main(String[] args)
  {
    if (args.length > 0) {
      for (int a = 0;  a < args.length;  ++a) {
        try {
          System.out.println("\""+args[a]+"\"\t\t"+new File(args[a]).toURL());
        } catch (MalformedURLException x) {
          x.printStackTrace();
        }
      }
    }
    else {
      new File2URL().show();
    }
  }
}

