/*
 *  Name:    $Id: FileInputPanel.java,v 1.6 2010/02/01 10:29:11 t724w Exp $
 * 
 *  Copyright 2009 Bundesamt für Informatik und Telekommunikation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ch.admin.bit.edec.evv.ui.swing;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.File;
import java.util.List;

import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class FileInputPanel extends JPanel {

	private final static int TEXT_LENGTH = 40;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final List<FileInputChangedListener> listeners;
	private final JFileChooser fileChooser;
	private final FileInputType type;

	private JTextField txtFile;

	public FileInputPanel(final FileInputType type, String value,
			final List<FileInputChangedListener> listeners) {

		this.listeners = listeners;
		this.type = type;

		firePathEvent(value);

		// set layout
		setLayout(new FlowLayout(FlowLayout.LEFT));
		fileChooser = new JFileChooser(value);
		txtFile = new JTextField(TEXT_LENGTH);
		txtFile.setText(value);

		txtFile.addKeyListener(new KeyListener() {

			public void keyTyped(KeyEvent e) {

			}

			public void keyReleased(KeyEvent e) {
				String path = ((JTextField) e.getSource()).getText();

				fileChooser.setCurrentDirectory(new File(path));

				for (FileInputChangedListener listener : listeners) {
					listener.onFilePathChanged(path, type);

				}
			}

			public void keyPressed(KeyEvent e) {

			}
		});

		txtFile.addMouseListener(new EditPopupMenuMouseListener());

		JLabel lblDescription = new JLabel(type.toString());

		add(lblDescription);
		add(txtFile);
		add(new FileChooserButton(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				showDialog();
			}
		}));

	}

	private void showDialog() {
		int returnVal = fileChooser.showOpenDialog(this);

		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();

			String path = file.getAbsolutePath();
			txtFile.setText(path);

			firePathEvent(path);
		}

	}

	private void firePathEvent(String path) {
		for (FileInputChangedListener listener : listeners) {
			listener.onFilePathChanged(path, type);

		}
	}

}
