package cz.vutbr.feec.gui;

import cz.vutbr.feec.project.GlobalParameters;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class ProgressBarRT extends Application {

	Task copyWorker; 
	private final Label label = new Label();
	public static ProgressBar pb = new ProgressBar();
	private final Button cancelButton = new Button("Cancel");
	final HBox hb = new HBox();
	private double value = 0;
	private int size;
	static Stage stage;

	@Override
	public void start(final Stage stage) {
		Group root = new Group();
		Scene scene = new Scene(root, 300, 150);
		stage.setScene(scene);
		stage.setMinHeight(150);
		stage.setMinWidth(300);
		stage.setTitle("Computing Routing Table");
		this.stage = stage;

		label.setText("Progress: ");
		/*
		 * final ProgressIndicator pin = new ProgressIndicator();
		 * pin.setProgress(value);
		 */
		hb.setSpacing(10);
		hb.setAlignment(Pos.CENTER);
		pb.setProgress(value);
		// hb.getChildren().addAll(label, pb, labelPerc, pin );
		hb.getChildren().addAll(label, pb, cancelButton);

		
		copyWorker = createWorker();
		pb.progressProperty().unbind();
		pb.progressProperty().bind(copyWorker.progressProperty());
		copyWorker.messageProperty().addListener(new ChangeListener<String>() {
			public void changed(ObservableValue<? extends String> observable,
					String oldValue, String newValue) {
				System.out.println(newValue);
			}
		});
		new Thread(copyWorker).start();

		cancelButton.setOnAction(new EventHandler<ActionEvent>() {
			public void handle(ActionEvent event) {
				cancelButton.setDisable(true);
				copyWorker.cancel(true);
				pb.progressProperty().unbind();
				System.out.println("cancelled.");
				stage.close();
			}
		});

		scene.setRoot(hb);
		stage.show();

	}

	public void setProgress(double d, int size) {
		value = (float) d;
		this.size = size;
	}

	public double getProgress() {
		return value;
	}

	public void closeStage() {
		stage.close();
	}

	public Task createWorker() {
		return new Task() {
			@Override
			protected Object call() throws Exception {
				/*
				while (value != size) {
					Thread.sleep(1000);// kazdu sekundu update
					updateProgress(value, size);
				}
				//zavriet okno (nefunguje, neviem preco)
				stage.close();
				return true;
			}
			*/
			
			  for (int i = 0; i < 10; i++) { 
			  Thread.sleep(1000);  
			  updateMessage("1000 milliseconds");
			  updateProgress(i,10); } return true; }
			 
		};
	}
}