/*************************************************************************
 * @author Ali Echihabi (ali_echihabi@ieee.org, ali.echihabi@souss.ca)
 *
 * Plugin for PHP unit Testing.
 * www.phpeclipse.de
 * 
 *************************************************************************/

package net.sourceforge.phpeclipse.phpunit;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import net.sourceforge.phpeclipse.phpunit.preferences.PHPUnitPreferencePage;
import net.sourceforge.phpeclipse.phpunit.reporthandling.ConnectionListener;
import net.sourceforge.phpeclipse.phpunit.reporthandling.XMLReportHandler;
import net.sourceforge.phpeclipse.phpunit.testpool.TestCase;
import net.sourceforge.phpeclipse.phpunit.testpool.TestPool;
import net.sourceforge.phpeclipse.phpunit.testpool.TestSuite;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.part.ViewPart;

public class PHPUnitView extends ViewPart {

	/*
	 * like J Unit a tree. The first level nodes are the test suites. children
	 * are nested test suites. leafs: test functions. hierarchy:
	 * package->testsuite1->testcase->test_function
	 */

	private static PHPUnitView view = null;

	private XMLReportHandler handler;

	private TestPool testPool;

	// private Button startButton;

	private ProgressInfoComposite progressInfoComposite;

	private ResultsInfoComposite resultsInfoComposite;

	// private SettingsInfoComposite settingsInfoComposite; //TODO: move
	// somewhere else, launcher, wizard or preferences.
	private FileDialog dialog;

	private String testSuiteToRun;

	private Action selectTestAction;

	private Action startTestAction;

	public PHPUnitView() {

		if (view == null)
			view = this;

	}

	public static PHPUnitView getDefault() {

		return view;
	}

	public void createPartControl(Composite parent) {

		// parent.setLayout(new FillLayout(SWT.VERTICAL));

		dialog = new FileDialog(parent.getShell());

		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 1;

		// set title and layout
		parent.setLayout(gridLayout);

		// Launch ToolBar:
		setActions();

		// Build the progress info Composites
		progressInfoComposite = new ProgressInfoComposite(parent);
		progressInfoComposite.setLayoutData(new GridData(
				GridData.GRAB_HORIZONTAL | GridData.FILL_HORIZONTAL
						| GridData.VERTICAL_ALIGN_BEGINNING));

		// Build the result info composite
		resultsInfoComposite = new ResultsInfoComposite(parent);
		resultsInfoComposite.setLayoutData(new GridData(GridData.GRAB_VERTICAL
				| GridData.FILL_BOTH));

		// build the settings composite
		// buildSettingsComposite(parent);

		// settingsInfoComposite = new SettingsInfoComposite(parent, SWT.NONE);

		// startButton = new Button(parent, SWT.CENTER);
		// startButton.setText("Start Tests");
		// startButton.addMouseListener(new MouseListener() {
		//
		// public void mouseDoubleClick(MouseEvent arg0) {
		//
		// }
		//
		// public void mouseDown(MouseEvent arg0) {
		//
		// try {
		// String testFile = settingsInfoComposite.getTestSuite();
		// startTests(testFile);
		// } catch (IOException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		//
		//
		// }
		//
		// public void mouseUp(MouseEvent arg0) {
		//
		//
		// }
		//
		// }); // end add action listener.

	}

	/**
	 * @param parent
	 */
	private void buildSettingsComposite(Composite parent) {

		// settingsInfoComposite = new Group(parent, SWT.NONE);
		// settingsInfoComposite.setText("Settings");
		// settingsInfoComposite.setLayout(new GridLayout(2,false));
		//		
		//		
		// //the test suite to launch
		// Label testSuiteLabel = new Label(settingsInfoComposite, SWT.NONE);
		// testSuiteLabel.setText("Test suite to run:");
		// //testSuiteLabel.setLayoutData(new GridData())
		// Text testSuiteText = new Text(settingsInfoComposite, SWT.NONE);
		//		
		// //the path to php
		// Label phpPathLabel = new Label(settingsInfoComposite, SWT.NONE);
		// phpPathLabel.setText("php Path:");
		// //testSuiteLabel.setLayoutData(new GridData())
		// Text phpPathText = new Text(settingsInfoComposite, SWT.NONE);

	}

	private void setActions() {

		final IActionBars actionBars = getViewSite().getActionBars();
		IToolBarManager toolBarManager = actionBars.getToolBarManager();

		selectTestAction = new Action() {

			public void run() {

				testSuiteToRun = dialog.open();
				startTestAction.setEnabled(true);
			}
		};

		selectTestAction.setText("Select Test Suite");
		selectTestAction.setToolTipText("Select Test Suite");
		selectTestAction
				.setImageDescriptor(PHPUnitImages.DESC_SELECT_TEST_SUITE);

		toolBarManager.add(selectTestAction);

		startTestAction = new Action() {

			public void run() {

				try {
					if (testSuiteToRun == null || testSuiteToRun == "")
						return;

					startTests(testSuiteToRun);
					// setEnabled(false);

				} catch (IOException e) {

					e.printStackTrace();
				}

			}

		};

		startTestAction.setText("Start Test");
		startTestAction
				.setToolTipText("Start Test Suite. Select a Test Suite first.");
		startTestAction.setImageDescriptor(PHPUnitImages.DESC_RUN_TEST_SUITE);
		startTestAction.setEnabled(false);

		toolBarManager.add(startTestAction);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ui.IWorkbenchPart#setFocus()
	 */
	public void setFocus() {

	}

	/**
	 * mark the given test as passed in the GUI.
	 * 
	 * @param testID
	 */
	private void markTestPassed(String testID) {

		// testid, use it in hashmap to retrieve tree item of test and
		// change icon color, increment pass counter, etc...

		testPool.getTest(testID).setVerdict(TestCase.PASS);

	}

	private void markTestFail(String testID) {

		testPool.getTest(testID).setVerdict(TestCase.FAIL);

	}

	public void startTests(String testSuite) throws IOException {

		// testSuite: the name of the file containing the suite we want to run.
		// we will put that test suite inside a contained that uses our
		// SocketResult.

		// reset from previous run
		reset();

		testSuite = testSuite.replaceAll("\\\\", "/");

		System.out.println("new: " + testSuite);

		// where the plugin's temp files should go
		String tempFolder = "C:\\tmp";
		String tempFileName = "temTest.php";

		// create the file.
		File testFile = new File(tempFolder + "/" + tempFileName);
		BufferedWriter out = new BufferedWriter(new FileWriter(testFile));

		out.write("<?php" + "\n");
		out.write("ob_start();" + "\n");

		String path = PHPUnitPlugin.getDefault().getPreferenceStore()
				.getString(PHPUnitPreferencePage.PHPUNIT_PATH);

		out.write("$path = \"" + path + "\";" + "\n");

		out.write("include_once($path . \"/phpunit_test.php\");" + "\n");
		out.write("include_once $path . \"/socketTestResult.php\";" + "\n");

		// include the test suite that we want to run.
		String testSuiteName = "";
		testSuiteName = testSuite.substring(testSuite.lastIndexOf('/') + 1,
				testSuite.lastIndexOf('.'));

		out.write("include_once(\"" + testSuite + "\");" + "\n");

		out.write("" + "\n");
		out.write("" + "\n");

		out.write("$suite = new TestSuite();" + "\n");
		out.write("$suite->addTest(new TestSuite(\"" + testSuiteName + "\"));"
				+ "\n");

		out.write("$result = new SocketTestResult();" + "\n");
		out.write("$suite->run($result);" + "\n");
		out.write("$result->report();	" + "\n");

		out.write("" + "\n");
		out.write("" + "\n");

		out.write("$output = ob_get_contents();" + "\n");
		out.write("$fileHandle = fopen('c:/tmp/phpOut.txt');" + "\n");
		out.write("fclose($fileHandle);" + "\n");

		out.write("ob_end();" + "\n");
		out.write("?>" + "\n");

		out.flush();
		out.close();

		listenForReports();

		try {
			Runtime.getRuntime().exec(
					"php.exe " + tempFolder + "/" + tempFileName);
		} catch (Exception e) {

			e.printStackTrace();
		}

		// testFile.delete();

	}

	/**
	 * 
	 */
	private void reset() {

		handler = new XMLReportHandler();
		testPool = new TestPool("Ali Baba");

		progressInfoComposite.resetInfo();
		resultsInfoComposite.resetInfo();

	}

	/**
	 * 
	 */
	private void listenForReports() {

		ConnectionListener conListener = new ConnectionListener();
		conListener.start(this);

	} // end of method

	/**
	 * handle this report: test passed, faile, end of all.
	 * 
	 * @param report
	 */
	public void handleReport(String report) {

		// delegate to the XML report handler.
		handler.handle(report, this);

	}

	/**
	 * @param command
	 * @param testCount
	 * @param testID
	 */
	public void handleCommand(String command, String[] args) {

		if (command.equals("startAll")) {

			// markTestingStarted(new Integer(testCount).intValue());

		} else if (command.equals("testSuiteStarted")) {

			String testID = args[0];
			String testCount = args[1];

			// createNewTestSuite("TestSuiteName: " + testID, testID, new
			// Integer(testCount).intValue());
			TestSuite suite = new TestSuite(null, "TestSuiteName: " + testID,
					testID, new Integer(testCount).intValue());
			testPool.addTestSuite(suite);

		} else if (command.equals("testStarted")) {

			String testID = args[0];
			String testCount = args[1];
			String testName = args[2];
			String parentTestSuiteName = args[3];

			testPool
					.addTest(new TestCase(testID, testName, parentTestSuiteName));

		} else if (command.equals("testFINISHED")) {

		} else if (command.equals("endAll")) {

		}

		update();

	}

	/**
	 * 
	 */
	private void update() {

		// progressInfoComposite.updateInfo(numTests, testPool.getNumTestsRun(),
		// numFailures, numErrors);
		progressInfoComposite.updateInfo(testPool);
		resultsInfoComposite.updateInfo(testPool);

	}

	/**
	 * @param currentTestID
	 * @param verdict
	 */
	public void setTestVerdict(String currentTestID, String verdict) {

		if (verdict.equals("passed"))
			markTestPassed(currentTestID);
		else
			markTestFail(currentTestID);

	}

	/**
	 * @param currentTestID
	 * @param exception
	 */
	public void addTestException(String currentTestID, String exception) {

		// TODO: decide how to show exceptions. don't show them for now.
		// reportArea.append(" test " + currentTestID + " exception: " +
		// exception + "\n");

	}

} // end of class