/* ----------------------------------------
 * Origin  : GFI INFORMATIQUE 
 * Project : CDPP Propagation Tool 
 * ----------------------------------------
 * History 
 * Version : 15/09/2016 : SCA : V2.2.2
 * 	Creation
 * ----------------------------------------
 */

package fr.tlse.irap.pt.client.controller.common;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.concurrent.Worker;
import javafx.scene.Cursor;
import javafx.scene.Node;

public class WaitProcess {

	private Thread waitThread = null;
	private Node parent;
	private int timeout;
	private static final int DEFAULT_TIMEOUT = 15; // 15 s

	/**
	 * Create a new waiting process 
	 * @param parent
	 * @param timeout in seconds
	 */
	public WaitProcess(Node parent, int timeout) {
		this.parent = parent;
		this.timeout = timeout;
		final Task<Object> waitProcessWorker = waitProcessWorker();

		waitProcessWorker.stateProperty().addListener(
				new ChangeListener<Worker.State>() {
					@Override
					public void changed(
							ObservableValue<? extends Worker.State> observableValue,
							Worker.State oldState, Worker.State newState) {
						if (newState == Worker.State.SUCCEEDED
								|| newState == Worker.State.FAILED
								|| newState == Worker.State.CANCELLED) {
							endCursor();
						}
					}
				});
		waitThread = new Thread(waitProcessWorker);
		waitThread.start();
		waitCursor();
	}

	/**
	 * Create a new waiting process 
	 * @param parent
	 */
	public WaitProcess(Node parent) {
		this(parent, DEFAULT_TIMEOUT);
	}


	/**
	 * Stop the waiting process 
	 */
	public void stop() {
		if (waitThread != null) {
			waitThread.interrupt();
		}
	}
	
	private Task<Object> waitProcessWorker() {
		return new Task<Object>() {
			@Override
			protected Object call() {
				for (int i=0; i<2*timeout; i++) {
					try {
						Thread.sleep(500);
					} catch (InterruptedException e) {
				        return true;
					}
				}
				return true;
			}
		};
	}

	private void waitCursor() {
		parent.setDisable(true);
		parent.getScene().setCursor(Cursor.WAIT);
	}

	private void endCursor() {
		parent.setDisable(false);
		parent.getScene().setCursor(null);
	}

}
