package lpv.gui.card;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.prefs.Preferences;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;

import lpv.simulation.injector.FileInjector;
import lpv.simulation.injector.Injector;

public class FileInjectorCard extends InjectorCard {

	private JTextField strengthField;
	private JTextField fileField;
	private JButton browseButton;

	public FileInjectorCard() {
		JPanel contents = new JPanel();
		contents.setLayout(new GridLayout(5, 2, 5, 5));
		
		contents.add(new JLabel("Multiplier: "));
		contents.add(strengthField = new JTextField("1.0"));
		
		contents.add(new JLabel("File: "));
		contents.add(fileField = new JTextField(20));
		
		contents.add(new JLabel());
		contents.add(browseButton = new JButton("Browse..."));
		browseButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent arg0) {
				Preferences pref = Preferences.userNodeForPackage(FileInjectorCard.class);
				File old = new File(pref.get("injector.file.path", ""));
				JFileChooser fileChooser;
				if(old.exists()) {
					fileChooser = new JFileChooser(old);
				} else {
					fileChooser = new JFileChooser();
				}
				
				fileChooser.setMultiSelectionEnabled(true);
				fileChooser.addChoosableFileFilter(new FileFilter() {
					@Override
					public boolean accept(File file) {
						return !file.isFile() || file.getName().endsWith(".lpv");
					}

					@Override
					public String getDescription() {
						return "LPV Dump (*.lpv)";
					}});
				
				int result = fileChooser.showOpenDialog(FileInjectorCard.this);
				if(result == JFileChooser.APPROVE_OPTION) {
					File[] files = fileChooser.getSelectedFiles();
					File file = fileChooser.getSelectedFile();
					pref.put("injector.file.path", file.getAbsolutePath());
					
					StringBuilder sb = new StringBuilder();
					for(int i = 0; i < files.length; i++) {
						sb.append(files[i].getAbsolutePath());
						if(i != files.length-1) {
							sb.append(File.pathSeparator);
						}
					}
					fileField.setText(sb.toString());
				} else {
					pref.put("injector.file.path", fileChooser.getCurrentDirectory().getAbsolutePath());
				}
			}});
		
		add(contents);
	}
	
	@Override
	public Injector createInjector() {
		try {
			float strength = Float.parseFloat(strengthField.getText());
			
			return new FileInjector(strength, fileField.getText());
		} catch(NumberFormatException e) {
			JOptionPane.showMessageDialog(this, "Invalid input. " + e.getMessage());
			return null;
		}
		
	}

}
