/*
	Copyright 2011 Daniel Pletea

	This file is part of T-Nano.

	T-Nano is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	T-Nano is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with T-Nano.  If not, see <http://www.gnu.org/licenses/>.
*/

import java.awt.Font;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * this class is made to analyze a circuit
 * 
 * @author Daniel Pletea
 * 
 */

public class GuiAnalyze extends Gui {

	//
	private static final long serialVersionUID = 1L;

	// these are the components that will appear in the user interface
	private JTextArea textArea;
	private JScrollPane areaScrollPane;
	private JProgressBar progressBar;

	// represents the progress of this action of analyzing the circuit
	private int progress;

	// the name of the circuit that is analyzed
	private String name;

	// these strings are used in order to create the final command
	private String exec;
	private String inputFile;
	private String parameters;
	private String progressFile;

	int ID;
	
	Process runtest;

	/**
	 * Constructor
	 * 
	 * @param name
	 *            - the name of the circuit: something.tnn
	 * @param exec
	 *            - the name of the executable file
	 * @param parameters
	 *            - the parameters for the command
	 */
	public GuiAnalyze(String name, int ID, String exec, String parameters) {

		super();

		// fedaback
		System.out.println("Constructor simulation");

		// init progress
		progress = 0;

		// creating the visual stuff
		textArea = new JTextArea();
		textArea.setBounds(150, 150, Main.fullSizeWidth - 260,
				Main.fullSizeHeight - 500);
		textArea.setFont(new Font("Arial", 0, 24));

		// create a scroll for the textArea
		areaScrollPane = new JScrollPane(textArea);
		areaScrollPane
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		areaScrollPane.setBounds(150, 150, Main.fullSizeWidth - 260,
				Main.fullSizeHeight - 500);
		this.add(areaScrollPane);

		textArea.append("The simulate is running...\n");
		textArea.append("Below is the progress of the simulation\n");

		// creating the progressBar which will show the user the state of the
		// analyzing process
		progressBar = new JProgressBar(0, 100);
		progressBar.setBounds(Main.fullSizeWidth / 2 - 100,
				Main.fullSizeHeight - 250, 200, 50);
		progressBar.setValue(progress);
		this.add(progressBar);

		this.ID = ID;
		this.name = name;
		this.exec = exec;
		this.parameters = parameters;

		// initiating the simulation
		initAnalyze();

		// begin the analyzing action
		analyze();
		
		closeTaskItem.setEnabled(true);
	}

	/**
	 * here is createed the command that will make the analyze action and this
	 * command is also executed
	 */
	private void analyze() {
		try {
			String nameOS = System.getProperty("os.name");

			String cmd = "";
			if (!nameOS.contains("Windows"))
				cmd = "./";

			cmd += exec + " ";

			cmd += inputFile + " " + parameters + progressFile;
			textArea.append(cmd + "\n");
			runtest = Runtime.getRuntime().exec(cmd);
		} catch (IOException e) {
			e.printStackTrace();
		}

		paint = true;
	}

	/**
	 * here the analyze action is ended
	 */
	private void endAnalyze() {
		BufferedReader in;
		try {

			Scanner scanner = new Scanner(parameters);

			// open the output file
			in = new BufferedReader(new FileReader(scanner.next()));

			// write its content int the textAre
			String string = in.readLine();
			while (string != null) {
				textArea.append(string + "\n");
				string = in.readLine();
			}
			in.close();

			String cmd = "rm " + progressFile;

			runtest.waitFor();
			Runtime.getRuntime().exec(cmd);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		// repaint
		paint = true;
	}

	private void initAnalyze() {

		inputFile = name.substring(0, name.length() - 3) + ANALYZE_FILE;
		progressFile = name.substring(0, name.length() - 4) + ID + "." + PROGRESS_FILE;

		inputFile = Singleton.getInstance().tranformName(inputFile);
		progressFile = Singleton.getInstance().tranformName(progressFile);

		paint = true;
	}

	@Override
	public void update() {
		BufferedReader in = null;
		Scanner scanner;
		int x = 0;

		if (paint) {
			repaint();
			paint = false;
		}

		// if the analyze action isn't finished
		if (progress < 100) {
			// try reading the progress file
			try {

				in = new BufferedReader(new FileReader(progressFile));

				// reading from progress file while another process is writing
				// in it
				scanner = new Scanner(in);
				while (scanner.hasNextInt()) {
					x = scanner.nextInt();
					if (x > progress)
						progress = x;
				}
				in.close();

				if (progress == 100)
					endAnalyze();
				progressBar.setValue(x);

				paint = true;

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
