import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;


public class GUIFileSearcher extends JPanel {
	public final static int WIDTH = 640;
	public final static int HEIGHT = 480;
	
	// Saves selected file for search - not ideal, but for some reason unable to parse text box.
	private File lastSelectedFile;
	
	public static void main(String[] args) {
		JFrame frame = new JFrame("File/Directory Searcher");
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frame.setSize(WIDTH, HEIGHT);
		frame.setLocationRelativeTo(null);

		GUIFileSearcher panel = new GUIFileSearcher();

		panel.init();
		frame.setContentPane(panel);

		frame.setVisible(true);
	}
	
	public void init() {
		GridBagLayout layout = new GridBagLayout();
		this.setLayout(layout);
		
		// Bar for selecting a file.
		JPanel fileSelect = new JPanel(new GridBagLayout());
		// Add descriptive label.
		fileSelect.add(new JLabel("Select a file"));
		// Field for holding file name.
		final JTextField nameField = new JTextField();
		// For some reason, we can't parse text into File, so we'll just
		// save file when chooser is used and not allow user to type in.
		nameField.setEditable(false);
		
		// Make text box fill remaining space.
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		c.weightx = .5;
		fileSelect.add(nameField, c);
		
		// Button to open JFileChooser.
		JButton selectFile = new JButton("Select");
		c.gridy = 0;
		fileSelect.add(selectFile);
		
		// Make button pop up file chooser.
		selectFile.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				int result = chooser.showOpenDialog(null);
				if (result == JFileChooser.APPROVE_OPTION) {
					lastSelectedFile = chooser.getSelectedFile();
					nameField.setText(chooser.getSelectedFile().getAbsolutePath());
				}
			}
		});
		
		// Add file choosing bar to interface (one of three 'bars').
		this.add(fileSelect, c);
		
		// Bar for entering search string.
		JPanel searchInput = new JPanel(new GridBagLayout());
		searchInput.add(new JLabel("Search string"));
		
		// Text field for entering string.
		final JTextField stringField = new JTextField();
		searchInput.add(stringField, c);
		
		// Button to trigger search.
		JButton doSearch = new JButton("Execute Search!");
		searchInput.add(doSearch);
		c.gridy = 1;
		this.add(searchInput, c);
		
		// Window to show results.
		final JTextArea results = new JTextArea();
		// Allows you to scroll through results.
		JScrollPane scroller = new JScrollPane(results);
		// Make it fill the rest of window.
		c.fill = GridBagConstraints.BOTH;
		c.weighty = .5;
		c.gridy = 2;
		this.add(scroller, c);
		
		// Make button call grep command and pipe results.
		doSearch.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				Runtime runtime = Runtime.getRuntime();
				try {
					ProcessBuilder builder = new ProcessBuilder("grep", stringField.getText(), "*");
					builder.directory(lastSelectedFile);
					Process proc = builder.start();
					
					String resultStr = "";
				
					BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
					String next = null;
					
					// Record all file names found.
					while ((next = in.readLine()) != null) {
						resultStr += next + "\n";
					}
					results.setText(resultStr);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		});
		
		// Open notepad for viewing selected file.
		results.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getButton() != MouseEvent.BUTTON1) {
					String selectedText = results.getSelectedText();
					if (selectedText != null) {
						Runtime runtime = Runtime.getRuntime();
						try {
							ProcessBuilder builder = new ProcessBuilder("notepad", selectedText);
							builder.directory(lastSelectedFile);
							Process proc = builder.start();
						} catch (Exception ex) {
							ex.printStackTrace();
						}
					}
				}
			}
		});
	}
}

